Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring java config - create list of beans also created in runtime

I have a list of gaming rooms which is created by Spring. Each rooms corresponds some rules (which is enum), and the code is:

@Bean
List<Room> rooms() {
    return Arrays.stream(Rules.values())
        .map(rule -> new Room(rule))
        .collect(Collectors.toList());
}

But now I need the rooms to be @Beans too: I want Spring to process @EventListener annotation in them. However, I don't want to declare them manually in config as the Rules enum can be updated in the future. How can I solve this problem? Thanks.

like image 259
awfun Avatar asked Feb 20 '17 10:02

awfun


1 Answers

It can be accomplished by invoking another method which is marked with @Bean i.e. creates Room bean as shown below

@Bean
List<Room> rooms() {
    return Arrays.stream(Rules.values())
        .map(rule -> room(rule))
        .collect(Collectors.toList());
}

@Bean
Room room(Rule rule) {
    return new Room(rule);
}

This should suffice without need of @EventListener.

Let know in comments if any more information is required.

like image 197
Bond - Java Bond Avatar answered Oct 03 '22 11:10

Bond - Java Bond