ApplicationContextAware怎么用
(1)方法类AppUtil实现ApplicationContextAware接口
@Component
public class AppUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
applicationContext = arg0;
}
@SuppressWarnings("unchecked")
public static Object getObject(String id) {
return applicationContext.getBean(id);
}
}
(2)实际开发中我们会有这种场景:
一个接口有多个实现,但是不同的场景调用不同的接口实现;
如下:通过type的不同来调用不同的service;
public class MyServiceFactory {
public static CoreService getCoreService( String type) {
if (StringUtils.isNotEmpty(type)) {
if ("1".equals(type) ) {
return BeanFactoryUtils.beanOfTypeIncludingAncestors(ApplicationContextUtil.getApplicationContext(), OrderServiceImpl.class)
}
if ("2".equals(type)) {
return BeanFactoryUtils.beanOfTypeIncludingAncestors(ApplicationContextUtil.getApplicationContext(), GoodsServiceImpl.class);
}
}else {
logger.error("类型,不能为空!");
return null;
}
}
通过type获取对应的service业务层
MyService myService = MyServiceFactory.getCoreService(type);
RespCode respCode = myService .getOrderInfo(id);
if (respCode != RespCode._000000) {
response.setErrorCode(respCode.getCode());
response.setErrorMsg(respCode.getDesc());
}
同学们在想一下,是不是还可以通过其他的手段实现呢?
- 当然,我们可以通过配置的方式实现同样的功能;
上代码!!!
<bean id="myServiceFactory" class="com.hequan..factory.MyServiceFactory">
<property name="myServiceMap">
<entry key="1" value-ref="orderServiceImpl"/>
<entry key="2" value-ref="goodsServiceImpl"/>
</property>
</bean>
(2)然后定义一个工厂
@Component
public class MyServiceFactory{
private Map<String, MyAccountService> myServiceMap;
public void setAccountServiceMap(Map<String, MyAccountService> myServiceMap) {
this.myServiceMap= myServiceMap;
}
/**
* 根据type,获取处理业务对象
*
* @param type
* @return
*/
public MyAccountService getAccountService(String type) {
LOG.info("type:{}", type);
return myServiceMap.get(type);
}
}
实际开发中为了减少代码的耦合,这两种方法还是不错滴!
转载:https://blog.csdn.net/hequan199411/article/details/102404385
查看评论