Let's say I have a preexisting enum.
enum Foo {
FOO1,
FOO2,
...
}
I now want to publish all members as spring beans. I could do:
@Bean("FOO1")
public Foo foo1(){
return Foo.FOO1;
}
@Bean("FOO2")
public Foo foo2(){
return Foo.FOO2;
}
...
And so on. Is there a way publish all enum members at once?
Commenters asked why I want to do this:
There is another component BarService
with
@Autowired
List<Bar> allTheBars;
It collects plenty of Bars already.
I need to make all members of enum Foo
available to BarService
, too. It would be easiest to have them implement Bar
and turn them into beans. Alternatively I could add them manually within BarService
but that requires me to change BarService
.
CodePudding user response:
There is always only one instance per enum value in a single JVM instance. You could just use Foo.FOO1
wherever you need it in the code without having to inject it as a bean.
CodePudding user response:
You can define your Enum
in one of configuration something like:
@Bean(name="EnumBeans")
Foo[] enums() {
return Foo.values();
}
Now, this will give you all values / members as soon as you access them:
@Autowired
@Qualifier(value="EnumBeans")
Foo[] enums;
..
public void accessor(){
for(Foo e:enums) {
System.out.println(e);
}
}