Java Reference
In-Depth Information
2-6. Reducing XML Configuration with Java Config
You enjoy the power of the DI container but want to override some of the configuration, or you simply
want to move more configuration out of the XML format and into Java where you can better benefit from
refactoring and type safety.
You can use Java Config, a project which has been in incubation since early 2005—long before Google
Guice hit the scene—and has recently been folded into the core framework.
How It Works
The JavaConfig support is powerful and represents a radically different way of doing things compared
with the other configuration options, via XML or annotations. It is important to remember that the
JavaConfig support can be used in tandem with the existing approaches. The simplest way to bootstrap
Java configuration is with a simple XML configuration file. From there, Spring will take care of the rest.
ClassPathXmlApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext("myApplicationContext.xml");
The configuration for that file looks the same as you'd expect:
<context:annotation-config />
<context:component-scan base-package="" />
This will let Spring find any classes marked with @Configuration . @Configuration is meta-annotated
with @Component , which makes it eligible for annotation support. This means that it will honor injection
using @Autowired , for example. Once your class is annotated with @Configuration , Spring will look for
bean definitions in the class. ( Bean definitions are Java methods annotated with @Bean .) Any definition is
contributed to the ApplicationContext and takes its beanName from the method used to configure it.
Alternatively, you can explicitly specify the bean name in the @Bean annotation. A configuration with one
bean definition might look like this:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class PersonConfiguration {
public Person josh() {
Person josh = new Person();
return josh ;
Search WWH ::

Custom Search