Tuesday, December 05, 2006

New annotation-based configuration for Spring


As you know, there is a new option for configuring Spring. XML is the most widely used configuration option for Spring, but with this new configuration type, based on annotations, we could change some "xml hell". We'll leave in peace the Groovy configuration, at least for now.
The developers for example, could use this for some form of "inner" application wiring, leaving the xml configuration for infrastructure.
You may take a look at the project site for news, but imagine a xml like this:

<beans>
<bean id="myCompany" class="package.Company"/>
<bean id="employee" class="Employee" scope="prototype">
<property name="company" ref="myCompany"/>
</bean>
</beans>

you could do it this way:

@Configuration
public class AppConfiguration {
@Bean
public Company myCompany() {
return new Company();
}

@Bean(scope = Scope.PROTOTYPE)
public Employee employee() {
Employee employee = new Employee();
employee.setCompany(myCompany());
return employee;
}
}

later initiating an ApplicationContext with a ConfigurationPostProcessor bean, even mixing beans from both methods:

<beans>
<bean class="package.AppConfiguration"/>
<bean class="org.springframework.beans.factory.java.ConfigurationPostProcessor"/>
<bean class="package.OtherClass">
<property name="employee" ref="employee"/>
</bean>
</beans>

Rod also shows us a new application context (by Costin Leau):

ApplicationContext oneConfig = new AnnotationApplicationContext(SimpleConfiguration.class.getName());

and

ApplicationContext aBunchOfConfigs = new AnnotationApplicationContext("**/configuration/*Configuration.class");

We will leave to our imagination a even more dynamic configuration, mixing loops and if/thens in the configuration bean!
The code could be found here. Enjoy it!

1 comment:

Lili Abreu said...

Hi, ola...
Want talk with you, please...
jasmimazull@hotmail.com

Beijo