Spring: Putting a private inner class as an outer member of a class?

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 an Outer bean and assign one of MapperA or MapperB as a property. Is it possible?

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

Edit: a little more information based on response reviews:

  • I was lazy with my example. I have a public setter / getter for a Mapper instance variable.

  • The reason all of the Mapper classes are internal is because there could potentially be many, and they will only be used in this class. I just don't need a ton of cool stuff in my project. Maybe the factory method is a better idea.

+4
source share
3 answers

Usually you need a setter for the Mapper inside Outer and an instance of the required Mapper . But since this:

  • private
  • interior

which becomes a bit complicated (as you defined). If you make them public, I'm sure you can use the instance with Outer$MapperA , etc. But that seems a bit unpleasant. So:

  • should they be internal and private?
  • perhaps Outer can take the string and determine whether to create instances of MapperA or MapperB . that is, there is a factory function here.

The simplest task is to really determine if they should be internal / private. If this is so, then in fact they should not be mentioned in the config, which should talk about public classes.

+1
source

Spring can create private classes. The actual problem with your configuration is that they are also not static , so you will need <constructor-arg .../> :

 <bean id="outer" class="mypackage.Outer"> <property name = "a"> <bean class = "mypackage.Outer.MapperA"> <constructor-arg ref = "outer" /> </bean> </property> </bean> 
+6
source

As far as I know, this is not possible until you make the usual public classes MapperA and MapperB .

But if you want to save them as internal private classes, you can manually enter them.

You need to create a method with @PostInit annotation and initialize the field a there ( a = new MapperA () for example, or something more complicated). With this approach, you should also verify that initialization callbacks are included in the spring configuration.

+1
source

Source: https://habr.com/ru/post/1302527/


All Articles