我有接口@Component Event
和类@Component BerlinEvent
来实现它。课程@Component Event
扩展EventService
并实施@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();}
}
。
在配置类上我有这个:
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));
}
主要是我制作豆子:
EventsManagerService
现在上课BerlinEvent
我需要创建一个包含Event
或$.trim(response) == 'hello'
对象的List,具体取决于创建的bean和每个具有不同值的对象,但我无法弄清楚如何做到这一点
答案 0 :(得分:1)
Spring可以将实现相同接口的所有bean自动装入列表中,如此
@Autowired
private List<Event> events;
默认情况下,只要零候选bean可用,自动装配就会失败;默认行为是将带注释的方法,构造函数和字段视为指示所需的依赖项。可以更改此行为,如下所示。为了避免这种情况,您需要将addtitonal参数传递给注释,如下所示:
@Autowired(required = false)
private List<Event> events;
以下是Spring文档的链接:https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-autowired-annotation
答案 1 :(得分:0)
在你的bean类中,你可以做到
@Service
public class EventsManagerService {
@Autowired
private ApplicationContext applicationContext;
private Map<String, Event> beans;
@PostConstruct
public void setMocks() {
beans = applicationContext.getBeansOfType(Event.class);
}
}
这将为您提供实现Events类的所有bean。