Spring:注入私有内部类作为外部类的成员?
我有以下类结构
public class Outer{
private Mapper a;
....
private class MapperA implements Mapper {
}
private class MapperB implements Mapper {
}
}
在我的 Spring 配置文件中,我想创建一个外部 bean,并将 MapperA 或 MapperB 之一指定为属性。这可能吗?
<bean id="outer" class="mypackage.Outer">
<property name="a" ?????='????' />
</bean>
编辑:根据答案的反馈,有更多信息:
我对上面的示例感到懒惰。我确实有一个用于 Mapper 实例变量的公共 setter/getter。
所有 Mapper 类都是内部类的原因是因为它们可能有很多,并且它们只会在此类中使用。我只是不想在我的项目中出现大量粗俗的课程。也许工厂方法是一个更好的主意。
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:
I got lazy with my above example. I do have a public setter/getter for the Mapper instance variable.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Spring可以实例化
private
内部类。您的配置的实际问题是它们也是非静态的,因此您需要一个
: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 .../>
:通常,您需要在
Outer
中为Mapper
提供一个设置器,以及所需的Mapper
的实例。但由于这些是:类,这变得有点棘手(正如您所确定的)。如果您将它们公开,我确信您可以使用 Outer$MapperA 等创建一个实例。但这似乎有点令人讨厌。那么:
最简单的事情就是真正确定它们是否需要内部/私有。如果是这样,那么它们确实不应该在配置中引用,配置应该讨论可公开访问的类。
Normally you'd need a setter for the
Mapper
withinOuter
, and an instance of the requiredMapper
. But as these are:classes, that becomes a bit tricky (as you've identified). If you make them public, I'm sure you could creae an instance using
Outer$MapperA
etc. But that seems a little nasty. So:MapperA
orMapperB
. i.e. there's some factory capability here.The simplest thing to do is to really determine if they need to be inner/private. If so, then they really shouldn't be referenced within the config, which should be talking about publicly accessible classes.
据我所知,除非您制作
MapperA
和MapperB
通常的公共类,否则这是不可能的。但如果您确实想将它们保留为内部私有类,那么您可以手动“注入”它们。
您需要使用
@PostInit
注释创建方法并初始化您的a
字段(例如a = new MapperA ()
或其他内容)更复杂)。使用这种方法,您还应该检查 Spring 配置中是否打开了初始化回调。As far as I know, it's impossible until you make
MapperA
andMapperB
usual public classes.But if you do want to keep them as inner private classes then you can "inject" them manually.
You'll need to create method with
@PostInit
annotation and initialize youra
field there (a = new MapperA ()
for example, or something more complex). With this approach you should also check that initialization callbacks are switched-on in your spring configuration.