Java – can I use spring’s @ component on enumerations?

I use spring 3.0 X and follow the enumeration singleton pattern of one of my implementations

public enum Person implements Nameable {
    INSTANCE;

    public String getName(){
        // return name somehow (Having a variable but omitted for brevity)
    }
}

Recently we started collecting these types through 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)
    }
}

The collection method is

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

After doing so, I observed a failure because spring could not initialize the enumeration class (which is understandable) My question is – is there any other way to mark my enumeration class as a bean? Or do I need to change my implementation?

Solution

If you really need to use enumeration based singleton (although spring bean is the default singleton in fact), you need to register the bean in the spring context in other ways For example, you can use XML configuration:

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

Or implement a 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;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>