To declare a bean, simply annotate a method with the @Bean
annotation or annotate a class with the @Component
annotation (annotations @Service
, @Repository
, @Controller
could be used as well).
When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory. By default, the bean name will be that of the method name.
We can create bean using one of three ways:
Using Java based Configuration: In Configuration file we need to declare bean using @bean annotation
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}
Using XML based configuration: For XML based configuration we need to create declare bean in application configuration XML i.e.
<beans>
<bean name="transferService" class="com.acme.TransferServiceImpl"/>
</beans>
Annotation-Driven Component: For annotation-driven components, we need to add the @Component annotation to the class we want to declare as bean.
@Component("transferService")
public class TransferServiceImpl implements TransferService {
...
}
Now all three beans with name transferService
are available in BeanFactory
or ApplicationContext
.