I would like to create a Spring Bean of a Inner class. If I have the following inner class B
:
package x.y.z; public class A { public class B { } }
I would like to create bean instance in my XML configuration files.
<bean class="x.y.z.A.B" name="innerBean" />
As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below.
To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory .
No. It is used to explicitly declare a single bean, rather than letting Spring do it automatically. If any class is annotated with @Component it will be automatically detect by using classpath scan. We should use @bean, if you want specific implementation based on dynamic condition.
In Spring framework, whenever a bean is used for only one particular property, it's advise to declare it as an inner bean. And the inner bean is supported both in setter injection 'property' and constructor injection 'constructor-arg'.
You cannot access your public static inner class with the dot (.
) notation, instead, use the currency ($
). An example:
<bean class="x.y.z.A$B" name="innerBean" />
This will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With