前言
在使用策略模式时,我们需要通过ApplicationContext获取某个接口的所有实现类。现有三种方式获取ApplicationContext,下面分别介绍这三个方式。
1、直接通过@Autowired注解获取
@Autowired
private ApplicationContext applicationContext;
2、通过实现ApplicationContextAware接口
@Service
public class OffbondMessageStrategy implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public IOffbondMessageService messageStrategy(String type) {
Map<String, IOffbondMessageService> fileMap = applicationContext.getBeansOfType(IOffbondMessageService.class);
return fileMap.get(OffbondMessageEnum.getServiceNameByCode(type));
}
}
3、通过构造函数注入
@Service
public class OffbondMessageStrategy {
private final ApplicationContext context;
public OffbondMessageStrategy(ApplicationContext context) {
this.context = context;
}
public IOffbondMessageService messageStrategy(String type) {
Map<String, IOffbondMessageService> fileMap = context.getBeansOfType(IOffbondMessageService.class);
return fileMap.get(OffbondMessageEnum.getServiceNameByCode(type));
}
}