Java 自动连线在非spring Singleton上不工作
我有一个非springJava 自动连线在非spring Singleton上不工作,java,spring,autowired,Java,Spring,Autowired,我有一个非spring公共类MySingleton,它有一个通过spring注入的MyBattis映射器,如下所示: public class MySingleton{ @Autowired MyMapper myMapper private List<MyPojo> myList; private MySingleton(){ myList = myMapper.getMyList(); } public stat
公共类MySingleton
,它有一个通过spring注入的MyBattis映射器,如下所示:
public class MySingleton{
@Autowired
MyMapper myMapper
private List<MyPojo> myList;
private MySingleton(){
myList = myMapper.getMyList();
}
public static MySingleton getInstance(){
if(instance == null){//first check
synchronized (MySingleton.class) {
if(instance == null){// second check
instance = new MySingleton();
}
}
}
return instance;
}
}
公共类MySingleton{
@自动连线
MyMapper MyMapper
私人名单;
二等兵迈辛格尔顿(){
myList=myMapper.getMyList();
}
公共静态MySingleton getInstance(){
如果(实例==null){//第一次检查
已同步(MySingleton.class){
如果(实例==null){//第二次检查
instance=new MySingleton();
}
}
}
返回实例;
}
}
myMapper
从未初始化,它在构造函数上始终为空。我已经测试过bean是在我的Singleton之前声明和创建的,我也尝试过Configurable
annotation,但没有任何效果
有人能帮我吗?为了在非托管类上检索托管Springbean,我编写了一个类,它完成了您想要做的事情
@Configuration
public class ApplicationContextProvider {
private static ApplicationContext context;
public ApplicationContextProvider(ApplicationContext context){
ApplicationContextProvider.context = context;
}
public static ApplicationContext getContext() {
if (Objects.isNull(ApplicationContextProvider.context)) {
throw new IllegalStateException("Context isn't available!");
}
return ApplicationContextProvider.context;
}
public static <E> E getBean(Class<E> bean){
return getContext().getBean(bean);
}
}
@配置
公共类ApplicationContextProvider{
私有静态应用上下文上下文;
公共ApplicationContextProvider(ApplicationContext上下文){
ApplicationContextProvider.context=上下文;
}
公共静态应用程序上下文getContext(){
if(Objects.isNull(ApplicationContextProvider.context)){
抛出新的IllegalStateException(“上下文不可用!”);
}
返回ApplicationContextProvider.context;
}
公共静态E-getBean(类bean){
返回getContext().getBean(bean);
}
}
要获取托管bean,只需ApplicationContextProvider.getBean(MyMapper.class)代码>您可以在非托管类中实现该接口。这将导致通过setter注入应用程序上下文,并允许您访问Spring生态系统的其余部分
然后您可以调用applicationContext.getBean(MyMapper.class)代码>注释MyMapper类@组件注释。这意味着当使用基于注释的配置和类路径扫描时,Spring框架将自动检测这些类以进行依赖注入。MyMapper此类未在IOC中注册为bean。首先用@Component或XML文件将MyMapper类注册为bean,然后运行,另外,您的类没有被注释为bean。使用@Autowired
注释构造函数,并将MyMapper
作为参数添加到构造函数中,或者调用MyMapper.getMyList()
在构造函数之外的另一个方法中。@Draken类的可能重复项MySingleton
未映射为Springbean。我认为这不是一个重复的问题。你能解释一下吗?