Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Spring Bean of a Inner class?

Tags:

java

spring

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" /> 
like image 391
Rubens Mariuzzo Avatar asked Aug 09 '12 15:08

Rubens Mariuzzo


People also ask

How do you make inner beans in the Spring?

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.

How do I create a Spring bean?

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 .

Can we use @bean inside @component?

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.

What is the use of inner beans in Spring?

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'.


1 Answers

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.

like image 176
Rubens Mariuzzo Avatar answered Sep 28 '22 05:09

Rubens Mariuzzo