项目中使用了大量的工厂类,采用了简单工厂模式:
通过该工厂类可以获取指定的处理器bean,这些处理器bean我们是从spring容器中获取的,如何获取,是通过实现ApplicationContextAware接口完成的。
@Component("handlerFactory") public class HandlerFactory implements InitializingBean, ApplicationContextAware { private static final Map<String, HandlerIntf> HANDLER_MAP = new HashMap<String, HandlerIntf>(); private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * 初始化工厂 * * @throws Exception */ @Override public void afterPropertiesSet() throws Exception { // 处理器1 HANDLER_MAP.put(TaskTypeConstants.RECON_DATA, applicationContext.getBean("handle1", HandlerIntf.class)); // 处理器2 HANDLER_MAP.put(TaskTypeConstants.BUSINESS_DATA, applicationContext.getBean("handle2", HandlerIntf.class)); } /** * 根据数据类型获取处理器 * * @param dataType * @return */ public SettleRequestHandlerIntf getHandler(String dataType) { HandlerIntf handler = HANDLER_MAP.get(dataType); if (null == handler) {
throw new AppException("0001", dataType + "不存在对应结算明细处理器"); } return handler; } }
1. 实现setApplicationContext方法
通过以上代码,可以看到继承了ApplicationContextAware接口,就要实现setApplicationContext方法,而方法中applicationContext,是spring容器注入进来的,这样我们就可以通过applicationContext变量获取spring容器中存在的bean。
2. 在spring中注入当前HandlerFactory类
刚才我们提到spring容器会自动将applicationContext注入进来,那么spring容器怎么识别到当前HandlerFactory类的?原因就在于HandlerFactory类加了注解:
@Component("handlerFactory")
或这种方式注入:
<bean id="handlerFactory" class="com.xxx.HandlerFactory"/>
这样spring才能扫描到它,并将applicationContext注入。