spring动态注入bean
//动态注入的方法
/**
* 通过BeanDefinition注册bean到spring context,无则加入,有则修改
* @param cxt spring context
* @param beanId
* @param classPath 类路径
* @param pvs bean属性值
*/
public void reg(ApplicationContext cxt, String beanId, String classPath, Map<String, Object> pvs){
BeanDefinition bdef = new GenericBeanDefinition() ;
bdef.setBeanClassName(classPath) ;
for (String p : pvs.keySet()) {
bdef.getPropertyValues().add(p, pvs.get(p)) ;
}
DefaultListableBeanFactory fty = (DefaultListableBeanFactory) cxt.getAutowireCapableBeanFactory() ;
fty.registerBeanDefinition(beanId, bdef) ;
}
/**
* 动态注销bean
* @param cxt spring context
* @param beanId
*/
public void destory(ApplicationContext cxt, String beanId){
DefaultListableBeanFactory fty = (DefaultListableBeanFactory) cxt.getAutowireCapableBeanFactory() ;
if(fty.containsBean(beanId)) {
fty.removeBeanDefinition(beanId);
}
}
/**
* 获取bean
* @param context spring context
* @param beanId
*/
public Object get(ApplicationContext cxt, String beanId){
try {
return cxt.getBean(beanId) ;
} catch (Exception e) {
//e.printStackTrace() ;
return null ;
}
}
//使用
//获取一个service来
String beanId = "xxxBeanServiceId" ;
ApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()) ;
Object obj = get(cxt, beanId) ;
if( obj == null ){
Map<String, Object> pvs = new HashMap<String, Object>() ;
pvs.put("xxService", xxService) ; //需要相应的set方法
pvs.put("xxxxxstring", "xxxxxxxxxxxxxxxxxxxxxxx") ;//需要相应的set方法
reg(cxt, beanId, cn.com.xx.xxxBeanServiceImpl/*service的实现类*/, pvs) ;
}
obj = get(cxt, beanId) ;
if( obj == null || !(obj instanceof xxxBeanService/*service接口*/) ){
setErrMsg("未能获取xxxBeanService") ;
return ERROR ;
}