Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create beans from inner class using spring

Tags:

spring

I was trying to define a class something below. Spring is not instantiating the beans.

    @Component
    public class A{
        @Component
        public class B{
         }
     }

Is there any way to let Spring create beans like above.

like image 234
Manoj Avatar asked Nov 20 '15 15:11

Manoj


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.

Does Spring support inner beans?

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

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.

Can we create two beans of same class in Spring?

If you define two beans of same class, without different bean id or qualifiers ( identifier) , Spring container will not be able to understand which bean to be loaded , if you try to access the bean by passing the classname and you will get NoUniqueBeanDefinitionException as there are two qualifying TestBean.


1 Answers

I don't think so because the inner class can not exist without its enclosing class. therefore it can only be injected into the enclosing Bean.

From Spring documentations:

An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always created with the outer bean. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean.

I think it is only possible only for static inner classes and not for not-static inner classes.

This should work:

    @Component
    public class A{
        @Component
        public static class B{
         }
     }
like image 129
Rafik BELDI Avatar answered Sep 28 '22 13:09

Rafik BELDI