简体   繁体   English

用Spring-Factory创建的ENUM bean,但从未调用@PostConstruct

[英]ENUM bean created with a Spring-Factory but the @PostConstruct is never called

I have an Enum : 我有一个枚举:

public enum MyEnum {

    INSTANCE;

    @Autowired
    Regroupements regroupements;

    @PostConstruct
    public void initi()
    {
        System.out.println("---------- i am not called!");
    }

    private MyEnum() {
        System.out.println("---------- i am called!");
    }

}

And a Spring-Factory 还有一个弹簧工厂

@Component
public class MyEnumFactory implements FactoryBean<MyEnum>{

    @Override
    public MyEnum getObject() throws Exception {
        return MyEnum.INSTANCE;
    }

    @Override
    public Class<?> getObjectType() {
        return MyEnum.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}

The problem is : when in call the method of the factory to give me the unique INSTANCE, the init() method is never called! 问题是:在调用工厂的方法给我唯一的INSTANCE时,永远不会调用init()方法! you'll notice that, as it is an Enum, the class don't have @Component annotation. 您会注意到,由于它是一个Enum,因此该类没有@Component批注。 it's why I use a factory. 这就是为什么我使用工厂。

what I want is to launch a post-construct, it doesn't matter the way. 我想要的是启动一个后构造,没关系。

You can't use enum as bean (and normally you don't have to), so you can neither use @PostConstruct on it, nor even autowire anything inside: your dependency Regroupements regroupements; 您不能将enum用作bean(通常不必这样做),因此您既不能在其上使用@PostConstruct ,也不能对其内部的任何东西进行自动装配:您的依赖项Regroupements regroupements; is going to be null . 将为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM