Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject parameters in enum constructor using Spring?

Tags:

java

enums

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?

like image 401
Julia Avatar asked Aug 09 '13 15:08

Julia


People also ask

How do you pass enum as parameter in spring boot?

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) { // ... }

Can you use enum in constructor?

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.

Can you inject an enum?

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.

Can enums have parameters?

You can have methods on enums which take parameters. Java enums are not union types like in some other languages.


2 Answers

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.

like image 53
Sotirios Delimanolis Avatar answered Oct 27 '22 00:10

Sotirios Delimanolis


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.

like image 26
saurav Avatar answered Oct 26 '22 22:10

saurav