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?
We can then use this enum as a RequestParameter in a Spring controller: @GetMapping("/mode2str") public String getStringToMode(@RequestParam("mode") Modes mode) { // ... } Or we can use it as a PathVariable: @GetMapping("/findbymode/{mode}") public String findByEnum(@PathVariable("mode") Modes mode) { // ... }
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.
You could try to inject your enum but how and what would you inject? It presents constant values and in addition it has private no args constructor. So the way you might have it working would be some JNDI lookup - that initializes dataProvider - inside your someMethod() or using some static context accessor.
You can have methods on enums which take parameters. Java enums are not union types like in some other languages.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With