java 我可以在枚举上使用 Spring 的 @Component 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5802634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I have Spring's @Component on enum?
提问by Premraj
I'm using Spring 3.0.x and following the enum singleton pattern for one of my implementatons.
我正在使用 Spring 3.0.x 并遵循我的一个实现的枚举单例模式。
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.
最近我们开始通过 Spring 收集这些类型,所以我需要将 @Component 添加到我的类中。
@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?
这样做后,我观察到失败,原因是 Spring 无法初始化枚举类(这是可以理解的)。
我的问题是 -
有没有其他方法可以将我的枚举类标记为 bean?
或者我需要改变我的实现?
采纳答案by axtavt
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:
如果您确实需要使用基于枚举的单例(尽管 Spring bean 在默认情况下是单例的),您需要使用某种其他方式在 Spring 上下文中注册该 bean。例如,您可以使用 XML 配置:
<util:constant static-field="...Person.INSTANCE"/>
or implement a FactoryBean
:
或实施一个FactoryBean
:
@Component
public class PersonFactory implements FactoryBean<Person> {
public Person getObject() throws Exception {
return Person.INSTANCE;
}
public Class<?> getObjectType() {
return Person.class;
}
public boolean isSingleton() {
return true;
}
}
回答by artbristol
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.
如果您使用 Spring 来管理依赖注入,则不需要使用枚举单例模式。您可以将 Person 更改为普通类。Spring 将使用单例的默认范围,因此所有 Spring 注入的对象将获得相同的实例。