我可以在枚举上使用Spring的@Component吗?

Pre*_*raj 15 java enums spring

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

public enum Person implements Nameable {
    INSTANCE;

    public String getName(){
        // return name somehow (Having a variable but omitted for brevity)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@Component
public enum Person implements Nameable {
    INSTANCE;

    public String getName(){
        // return name somehow (Having a variable but omitted for brevity)
    }
}
Run Code Online (Sandbox Code Playgroud)

和收集方法是

@Autowired
public void collectNameables(List<Nameable> all){
    // do something 
}
Run Code Online (Sandbox Code Playgroud)

在这样做后,我观察到失败和原因是Spring无法初始化枚举类(这是可以理解的).

我的问题是 -
有没有其他方法可以将我的枚举类标记为bean?
或者我需要改变我的实施?

axt*_*avt 7

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

<util:constant static-field="...Person.INSTANCE"/>
Run Code Online (Sandbox Code Playgroud)

或实施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;
    }
}
Run Code Online (Sandbox Code Playgroud)


art*_*tol 5

如果您使用Spring来管理依赖注入,则不需要使用枚举单例模式.您可以将您的人员更改为普通班级.Spring将使用单例的默认范围,因此所有Spring注入的对象都将获得相同的实例.