Can I have Spring's @Component on enum?

前端 未结 2 1456
失恋的感觉
失恋的感觉 2020-12-31 03:28

I\'m using Spring 3.0.x and following the enum singleton pattern for one of my implementatons.

public enum Person implements Nameable {
    INSTANCE;

    pu         


        
相关标签:
2条回答
  • 2020-12-31 03:59

    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"/>
    

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-31 04:10

    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.

    0 讨论(0)
提交回复
热议问题