Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Injecting a private inner class as an outer class's member?

I have the following class structure

public class Outer{
    private Mapper a;
    ....

    private class MapperA implements Mapper {

    }

    private class MapperB implements Mapper {

    }
}

In my Spring config file I would like to create a an Outer bean, and assign one of MapperA or MapperB as a property. Is this possible?

<bean id="outer" class="mypackage.Outer">
    <property name="a" ?????='????' />
</bean>

Edit: Some more info, based on the feedback from answers:

  1. I got lazy with my above example. I do have a public setter/getter for the Mapper instance variable.

  2. The reason all of the Mapper classes are inner classes is because there could potentially be many of them, and they will only ever be used in this class. I just don't want a ton of cruft classes in my project. Maybe a factory method is a better idea.

like image 913
D.C. Avatar asked Jan 22 '23 12:01

D.C.


1 Answers

Spring can instantiate private inner classes. The actual problem with your config is that they are also non-static, so you need a <constructor-arg .../>:

<bean id="outer" class="mypackage.Outer"> 
    <property name = "a">
        <bean class = "mypackage.Outer.MapperA"> 
            <constructor-arg ref = "outer" />
        </bean>
    </property>
</bean> 
like image 102
axtavt Avatar answered Jan 25 '23 02:01

axtavt