简体   繁体   中英

How to inject parameters in enum constructor using Spring?

I have an enum like this:

public enum SomeEnum {
    ONE (new MyClass()),
    TWO (new MyClass());

    private final MyClass instance;

    private SomeEnum(MyClass instance) {
        this.instance = instance;
    }
}

How can I pass MyClass instance to the enum constructor from Spring context? Is it even possible?

I need it because I pass some parameters from config (.properties file) into MyClass instance while I create it. Now I'm doing it in xml-file with beans, maybe there is another way?

You cannot do this.

In this official Java tutorial on Enum Types, it states

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

Since an Enum is supposed to be a constant set of constants, it doesn't make sense to be able to create new ones, so the constructors are not available, even through reflection.

Even when we talk in context of Spring , i think that is also not possible.

You cannot instantiate enums because they have a static nature. So I think that Spring IoC can't create enums as well.

please have a look at Spring IoC chapter.

What you can do however, is leverage MyClass within the enum to encapsulate some 'constant' behaviour. You can take this as far as you like ( not that it's necessarily a great idea... ) for example you might use some static factory class to load property values based on those constant names passed in.

public enum SomeEnum {
    ONE ("propname1"),
    TWO ("propname2");

    private final MyClass instance;

    private SomeEnum(String str) {
        this.instance = MyClassFactory.newInstance(str);
    }

    public Object doSomething(int value) {
        return instance.doSomething(value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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