CT Bean - prasadtalasila/BITS-Darshini GitHub Wiki
@Bean
is a method level annotation. This method basically returns an object (Bean) of some class which is required to be injected into some @Autowired
field in a some other class. (Think of a Bean as nothing but a non-POJO, that is autowired somewhere inside a Class according to the Dependency Injection Principle). The Spring IoC Container "contains" all beans, and provides them for autowiring whenever asked for.
Spring automatically creates beans for any class marked as @Component
. Sometimes there may be a possibility that the Spring IoC Container doesn't contain the object(bean) required by our class. This is where the @Bean
annotation comes to help. We can explicitly create our class dependency object in the ClassConfig File using @Bean
(example). This also gives us the option of customizing our object before being picked up by the IoC Container out for autowiring.
Example:
Consider two classes A and B
ClassA{
@Autowired
ClassB varName;
}
ClassB{
public int x=0;
public int y=0;
}
Let's say class B isn't defined with @Component Annotation so now the Spring IoC has no bean of type Class B. Without explicitly creating a bean of type ClassB and ClassA objects can't be created as the autowiring will fail for varName
will fail. We can solve this by using @Bean
. We do the following:
ClassAConfig{
ClassB temp = new ClassB();
temp.x =10;
temp.y =100;
@Bean //opt1
public ClassB varName(){
return new ClassB();
}
@Bean //opt2
public ClassB varName(){
return temp;
}
}