问题:
在我们开发过程中总会遇到比如在某些场合中需要使用service或者mapper等读取数据库,或者某些自动注入bean失效的情况
解决方法:
1.在构造方法中通过工具类获取需要的bean
工具类代码:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author
* @decription 通过工具类获取需要的的bean
*/
@Component
public class BeanContextUtils implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanContextUtils.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
注入代码:

2.通过set方法注入bean
private static SysDictFeignService service;
@Autowired
public void setSysDictFeignService(SysDictFeignService service){
DictValidator.service = service;
}
3.通过有参构造方法传入

本文介绍了在Spring开发中如何处理服务或mapper依赖问题,包括使用工具类获取ApplicationContext中的bean,通过@Autowired注解的set方法注入bean,以及通过构造方法传入bean的解决方案。
1718

被折叠的 条评论
为什么被折叠?



