In Spring 3 we can also create a bean using java file instead of XML.It is alternate way to create the bean, you can also use xml based configuration.
HelloWorld.java
package com.babita;
public class HelloWorld {
public void printMessage(String message)
{
System.out.println("Hello World From "+message);
}
}
JavaConfig.java
package com.babita;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorld();
}
}
Now define the below class to run the code:
MainApp.java
package com.babita;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args)
{
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printMessage("Spring 3.0");
}
}
In above Example we can see that the JavaConfig.java file can put @Configuration annotation to indicate that is core spring configuration file and @Bean annotation defines the name of bean and finally we can load the JavaConfig.java class via AnnotationConfigApplicationContext to instantiate the bean.
Hope this will help you :)
0 Comment(s)