Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static nested class as Spring bean

How do I create an instance of a static nested class as a Spring bean in an XML configuration file? For example:

package com.x.y;
public class A {
    public static class B {
    ...
    }
}

So that I have a Spring-managed bean of class B?

like image 620
z12345 Avatar asked Jan 25 '12 15:01

z12345


People also ask

How do you define a bean for static inner class in 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.

Can a Spring bean have static methods?

Yes, A spring bean may have static methods too.

Can nested classes be static?

Terminology: Nested classes are divided into two categories: non-static and static. Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class.

Can a bean method be static?

By marking this method as static , it can be invoked without causing instantiation of its declaring @Configuration class, thus avoiding the above-mentioned lifecycle conflicts. Note however that static @Bean methods will not be enhanced for scoping and AOP semantics as mentioned above.


1 Answers

Using A$B syntax, which is how the classloader sees inner classes. So assuming package com.x.y, then:

<bean id="myBean" class="com.x.y.A$B"/>
like image 195
skaffman Avatar answered Sep 28 '22 07:09

skaffman