Can I have Spring's @Component on enum?

前端 未结 2 1465
失恋的感觉
失恋的感觉 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:

    
    

    or implement a FactoryBean:

    @Component
    public class PersonFactory implements FactoryBean {
        public Person getObject() throws Exception {
            return Person.INSTANCE;
        }
    
        public Class getObjectType() {
            return Person.class;
        }
    
        public boolean isSingleton() {
            return true;
        }
    }
    

提交回复
热议问题