Skip to content

Spring Configurable Magic

April 3, 2013

Spring framework has several modules that provide a range of services, many of these modules Can work just for managed Objects (Spring Beans) Some examples about these services are Dependency Injection, Transaction Management, AOP Services , etc.
Everything is fine when we are using Objects as Services, so they are managed by by Spring with a specific scope. But sometimes we need our domain objects have these services. Usually domain objects are created with new keyword so they cannot be managed by default with spring.
In my Previous post (How to use Events in SpringĀ 3.x) we had a domain object with name Order. for decoupling between object we used events.
But just Managed beans can raise event in Spring framework (Probably every Framework you know and has this feature).
Spring introduce an annotation with name Configurable. Using this annotation on our domain objects make them Managed by spring.
But how does it work:
Configurable for its purpose needs AspectJ Compiler, your class needs Byte Code Enhancement in Compile Time or Load Time until can satisfy your requirements.

I want to bring you a simple sample about how to configure and use Configurable power in your applications.

It is a good practice to have an Environment Object that all the system can access its properties to catch information about system. For example we need to know the current time of system, simple solution is to use Calendar.getInstance().getTime() orĀ  new Date()

but there are some defects, your code will not be testable for parts that you need to test date assertion ( I will write a series of post bout Test and Testable codes as soon as possible) .

The other problem is when you want your system work with Pseudo clock. as an example your client wants to work with system in holidays as the last non holiday date.

So it is valuable to have a mechanism for these requirements. As a simple solution in this sample i will create An Environment Interface that have one method ( getCurrentTime()). Everywhere in code if i need the time of system i will use this method. Environment interface must be injected in my objects until i can happily use this method. Spring beans do not have any problem to using Environment, but in our domain objects we have to use Configurable Annotation.

If you use Maven you will need to added these dependencies to your pom:

 <groupId>org.springframework</groupId>
 <artifactId>spring-aspects</artifactId>
 <version>3.1.1.RELEASE</version>
  <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjrt</artifactId>
 <version>1.6.8</version>
 </dependency>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjweaver</artifactId>
 <version>1.6.8</version>
 </dependency>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjtools</artifactId>
 <version>1.6.8</version>
 </dependency>

To compile your application with maven you can use following Aspectj-maven-plugin configuration :


<build>
 <plugins>
 <plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>aspectj-maven-plugin</artifactId>
 <version>1.4</version>
 <configuration>
 <showWeaveInfo>true</showWeaveInfo>
 <source>1.6</source>
 <target>1.6</target>
 <Xlint>ignore</Xlint>
 <complianceLevel>1.6</complianceLevel>
 <encoding>UTF-8</encoding>
 <verbose>false</verbose>
 <aspectLibraries>
 <aspectLibrary>
 <groupId>org.springframework</groupId>
 <artifactId>spring-aspects</artifactId>
 </aspectLibrary>
 </aspectLibraries>
 </configuration>
 <executions>
 <execution>
 <goals>
 <goal>compile</goal>
 <goal>test-compile</goal>
 </goals>
 </execution>
 </executions>
 <dependencies>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjrt</artifactId>
 <version>1.6.8</version>
 </dependency>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjtools</artifactId>
 <version>1.6.11</version>
 </dependency>
 </dependencies>
 </plugin>
 </plugins>
 </build>

If you use IDE for compiling your code don’t forget to change its compiler to AspectJ. you can find it in your local maven respository in aspectjrt directory.

Assume there is a Product class and we would like to know the date of its creation, and the date if its sale.


@Configurable(preConstruction = true)
 public class Product {
 private final String name;
 private final String description;
 private final Date createDate;
 private Status status;
 private Date saleDate;
 @Autowired
 private Environment environment;

public Product(String name, String description) {
 this.name = name;
 this.description = description;
 this.status = Status.PENDING;
 this.createDate = environment.getCurrentDate();
 }

public void sell() {
 this.status = Status.SALE;
 this.saleDate = environment.getCurrentDate();
 }

public Date getCreateDate() {
 return createDate;
 }

public Date getSaleDate() {
 return saleDate;
 }

public static enum Status {
 PENDING, SALE;
 }
 }

Product is a very simple class, we used preConstruction=true because our product construction need to use environment.

Environment and its implementations are very simple too:


public interface Environment {
 Date getCurrentDate();
 }

public class DefaultEnvironment implements Environment {
 @Override
 public Date getCurrentDate() {
 return new Date();
 }
 }

public class MockEnvironment implements Environment {
 private Date date;
 @Override
 public Date getCurrentDate() {
 return this.date;
 }

public void setCurrentDate(Date date){
 this.date = date;
 }

}

MockEnvironment is created in test packages, because we need this class just in our tests. Instead of using this class you can use some mock library as Mocktio and an extension on it (Springockito). But in this sample our focus is not on them.

Our tests are very simple too:


@ContextConfiguration({"classpath*:context.xml","classpath*:test-context.xml"})
 public class ProductTest extends AbstractJUnit4SpringContextTests {
 final Date time = Calendar.getInstance().getTime();
 @Autowired
 Environment environment;

@Before
 public void before() {

((MockEnvironment) this.environment).setCurrentDate(time);
 }

@Test
 public void created_product_should_have_current_environment_date() {
 final Product product = new Product("", "");
 Assert.assertEquals(time, product.getCreateDate());

}

@Test
 public void sell_should_set_createDate_to_now(){
 final Product product = new Product("", "");
 product.sell();
 Assert.assertEquals(time, product.getSaleDate());

}
 }

I hope this post can help you to using this magic feature of Spring.
Please give me feedback and your opinions about my blog.

You can download source code from : https://github.com/psycho-ir/Spring-Configurable.git

About these ads

From → JAVA, Spring

2 Comments
  1. Alborz permalink

    thank you keep up good work

  2. this is really good, you might also think of posting on this blog as a guest blogger? http://www.mahderjava.blogspot.com

    I like the post BTW

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: