我可以在枚举上使用Spring的@Component吗? [英] Can I have Spring's @Component on enum?

查看:303
本文介绍了我可以在枚举上使用Spring的@Component吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring 3.0.x并遵循我的一个实现的枚举单例模式。

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)
    }
}

最近我们开始通过Spring收集这些类型,所以我需要将@Component添加到我的班级。

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)
    }
}

和收集方法是

@Autowired
public void collectNameables(List<Nameable> all){
    // do something 
}

执行此操作后,我观察到失败和原因是Spring无法初始化枚举类(这是可以理解的)。


我的问题是 -

有没有其他方法可以将我的枚举类标记为bean?

或者我需要更改我的实现?

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?

推荐答案

如果你真的需要使用基于枚举的singleton(尽管Spring bean默认是单例),你需要使用其他方法在Spring上下文中注册该bean。例如,您可以使用XML配置:

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:

<util:constant static-field="...Person.INSTANCE"/>

或实现 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;
    }
}

这篇关于我可以在枚举上使用Spring的@Component吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆