bio photo

Twitter Github

Since version 3.0 spring supports java based configuration. The main quibble i have with spring xml configuration is the readability. Once your code base grows the spring xml files become less readable. With java based congfiguration you get good readbility.

To use the java based configuration one has to annoate the class with @Configuration and the beans with @Bean

1 @Configuration
2 public class SpringConfig {
3 	@Bean
4 	public MyBean myBean() {
5 		return new MyBeanImpl();
6 	}
7 }

You can now configure the application context in the following way

1 public static void main(String[] args) {
2     ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
3     MyBean myBean = ctx.getBean(MyBean.class);
4 }

The very interesting thing is that dependencies are stasified using method invokcation, which is very intutive.

 1 @Configuration
 2 public class SpringConfig {
 3 	@Bean
 4 	public MyBean myBean() {
 5 		return new MyBeanImpl(myDepBean());
 6 	}
 7 	@Bean
 8 	public MyDepBean myDepBean() {
 9 		return new MyDepBeanImpl();
10 	}
11 }

The most useful feature is that it is possible to configure two beans of the same type very easily. This overcomes the problems faced with spring configuration by annotation.

 1 @Configuration
 2 public class SpringConfig {
 3 	@Bean
 4 	@Qualifier(value="retryProcessor")
 5 	public MyProcessor myRetryableProcessor() {
 6 		return new MyProcessorImpl(retryFailureStrategy());
 7 	}
 8 	@Bean
 9 	@Qualifier(value="skipProcessor")
10 	public MyProcessor mySkipProcessor() {
11 		return new MyProcessorImpl(skipFailureStrategy());
12 	}
13 	@Bean
14 	public FailureStrategy retryFailureStategy() {
15 		return new RetryFailureStrategyImpl();
16 	}
17 
18 	@Bean
19 	public FailureStrategy skipFailureStategy() {
20 		return new skipFailureStrategyImpl();
21 	}
22 }

The beans now can be accessed in the following way

1 public static void main(String[] args) {
2     ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
3     MyProcessor retry=ctx.getBean("retryProcessor");
4     MyProcessor skip=ctx.getBean("skipProcessor");
5 }

By default the scope of the beans are singletons. You can define the scope using the @Scope.

More information is available at Spring Documentation