There are three different ways to configure Spring Bean.
XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:
<bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>
Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
@Configuration
@ComponentScan(value="com.journaldev.spring.main")
public class MyConfiguration {
@Bean
public MyService getService(){
return new MyService();
}
}
To get this bean from spring context, we need to use following code snippet:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
MyConfiguration.class);
MyService service = ctx.getBean(MyService.class);
Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes. For example:
<context:component-scan base-package="com.journaldev.spring" />