4/29/2012

How to use Spring Java Config

Filed under: — Aviran Mordo

With Spring framework you can configure your beans with Java code instead of xml files, however mixing the two might cause unexpected results, if you don’t use Java config correctly.

One example we were facing when we used mixed configuration methods (xml and java) is that beans you reference in your Java config are not yet initialized thus you might get nulls in places you don’t expect to get them.

Here is an example how you should NOT use Java config:

Never user members annotated as resource and use them in your Bean definition. Spring will not guarantee that the bean will be injected on that time.


BAD example

class MyConfig {
@Resource
private MyResource myResource

@Bean
MyClientBridge myClientBridge(){
return new MyClientBridge(myResource);
}
}

In above code, myResource may be null.

So how can we use it properly?
You can still define beans similar in both xml files and Java Config however when you use them in Java Config you need to pass them as arguments to the bean definition. If the arguments are Spring beans then Spring will inject them with the relevant dependencies.

Here is the CORRECT usage:


Good Example

class MyConfig {

@Bean
MyClientBridge myClientBridge(MyResource myResource){
return new MyClientBridge(myResource);
}
}

Spring will now inject the myResource to the method and make sure it is initialized before it does that.

Powered by WordPress