<bean id="Hello" class="com.mj.Hello"/>
To use the bean you wrote code like
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml") ;
BeanFactory bf = (BeanFactory) ac ;
Hello h = bf.getBean("Hello")
h.someMethod() ;
Let us write a new spring application using no XML. Step1: Define the bean interface and implementation
public interface Greeting {
public String getMessage() ;
}
public class NewYearGreeting implements Greeting {
public String getMessage() {
return "Happy New Year" ;
}
}
public class BirthDayGreeting implements Greeting {
public String getMessage() {
return "Happy Birthday" ;
}
}
Step 2: Define the bean configuration in JAVAThe bean definitions are created by writing a class and annotating it with @Configuration. The individual beans are defined by annotating the method that creates the bean with @Bean.
@Configuration
public class GreetingSpringConfig {
@Bean(name="newyear")
public Greeting newyearGreeting() {
return new NewYearGreeting() ;
}
@Bean(name="birthday")
public Greeting birthdayGreeting() {
return new BirthDayGreeting() ;
}
}
Step 3: Use the beans from a client
public class GreetingSample {
public static void main(String args[]) {
ApplicationContext ac = new
AnnotationConfigApplicationContext(GreetingSpringConfig.class) ;
Greeting g = (Greeting) ac.getBean("newyear") ;
System.out.println(g.getMessage()) ;
g = (Greeting) ac.getBean("birthday") ;
System.out.println(g.getMessage()) ;
}
Note that instead of using ClassPathXmlApplicationContext ,we used AnnotationConfigApplicationContext. AnnotionConfigApplicationContext can process not just @Configuration annotated classes, but also JSR 330 annotated classes. If you don'nt like switching between JAVA & XML , then Java config is simple way of wiring your spring beans.