Spring: Easy way to use Dependency Injection in enum classes?


#1

ATM I have code like this:

enum class Process(val implementation: ProcessInterface) {
    FOO(SomeProcess())
}

Is it somehow possible to use dependency injection within SomeProcess? Those processes should be very generic, some have models, repositories and stuff and should mainly maintain stuff on there own.

I’m using latest spring boot.


#2

I would write something like this:

enum class Process {
    FOO;

    @Autowired
    lateinit var implementation: ProcessInterface
}
@Bean
fun someProcess() = SomeProcess()

#3

I don’t know enough about your design, but have you thought about sealed classes instead of an enum?

I would avoid field injection whenever possible!


#4

Ah, sorry, it’s different in this case. Each implementation (classes that implement ProcessInterface) should be able to use @Autowired.