我可以在枚举上使用 Spring 的 @Component 吗?
我正在使用 Spring 3.0.x 并遵循我的实现之一的枚举单例模式。
public enum Person implements Nameable {
INSTANCE;
public String getName(){
// return name somehow (Having a variable but omitted for brevity)
}
}
最近我们开始通过 Spring 收集这些类型,所以我需要将 @Component 添加到我的类中。
@Component
public enum Person implements Nameable {
INSTANCE;
public String getName(){
// return name somehow (Having a variable but omitted for brevity)
}
}
收集方法是
@Autowired
public void collectNameables(List<Nameable> all){
// do something
}
这样做之后我观察到失败,原因是 Spring 无法初始化枚举类(这是可以理解的)。
我的问题是 -
有没有其他方法可以将我的枚举类标记为 bean?
或者我需要改变我的实施?
I'm using Spring 3.0.x and following the enum singleton pattern for one of my implementatons.
public enum Person implements Nameable {
INSTANCE;
public String getName(){
// return name somehow (Having a variable but omitted for brevity)
}
}
Recently we started to collecting those types via Spring so I need to add @Component to my class.
@Component
public enum Person implements Nameable {
INSTANCE;
public String getName(){
// return name somehow (Having a variable but omitted for brevity)
}
}
and collecting method is
@Autowired
public void collectNameables(List<Nameable> all){
// do something
}
After doing this I observed failures and cause was Spring cannot intialize enum classes (which is understandable).
My question is -
Is there any other way usign which I can mark my enum classes as a bean ?
Or i need to change my implementation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确实需要使用基于枚举的单例(尽管 Spring bean 默认情况下是单例),则需要使用其他方式在 Spring 上下文中注册该 bean。例如,您可以使用 XML 配置:
或实现一个
FactoryBean
:If you really need to use enum-based singleton (despite the fact that Spring beans are singletons by default), you need to use some other way to register that bean in the Spring context. For example, you can use XML configuration:
or implement a
FactoryBean
:如果您使用 Spring 来管理依赖项注入,则不需要使用枚举单例模式。您可以将您的 Person 更改为普通类。 Spring将使用默认的单例范围,因此所有Spring注入的对象将获得相同的实例。
You won't need to use the enum singleton pattern if you're using Spring to manage dependency injection. You can change your Person to a normal class. Spring will use the default scope of singleton, so all Spring-injected objects will get the same instance.