Vhalad
Vhalad

Reputation: 119

Make List of Spring Bean

I have interface EventService and class @Component Event implementing it. Class @Component BerlinEvent extends @Component Event and implements EventService.

On configuration class I have this:

@Configuration
public class Configuration {

    //Country name
    @Bean
    @ConditionalOnProperty(name = "country", havingValue = "UK")
    public Event defaultService(){return new Event();}

    @Bean
    @ConditionalOnProperty(name = "country", havingValue = "germany", matchIfMissing = true)
    public Event germanyEventService(){return new BerlinEvent();}
}

And on main I make the bean:

public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(EventscraperApplication.class, args);

        EventsManagerService eventsManager = context.getBean(EventsManager.class);
        eventsManager.run(context.getBean(Event.class));
    }

Now on class EventsManagerService I need to make a List with either BerlinEvent or Event objects depending on which bean was created and each object with different values but I cant figure out how to do it

Upvotes: 0

Views: 614

Answers (2)

Ivan
Ivan

Reputation: 8758

Spring could autowire all beans that implement the same interface into the list like this

@Autowired
private List<Event> events;

By default, the autowiring fails whenever zero candidate beans are available; the default behavior is to treat annotated methods, constructors, and fields as indicating required dependencies. This behavior can be changed as demonstrated below. To avoid that you need to pass addtitonal parameter to annotation like this:

@Autowired(required = false)
private List<Event> events;

Here is the link to Spring documentation: https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-autowired-annotation

Upvotes: 1

best wishes
best wishes

Reputation: 6644

In you bean class, you can just do

@Service
public class EventsManagerService {

    @Autowired
    private ApplicationContext applicationContext;

    private Map<String, Event> beans; 

    @PostConstruct
    public void setMocks() {
        beans = applicationContext.getBeansOfType(Event.class);  
    }
}

This will get you all the beans implementing Events class.

Upvotes: 0

Related Questions