自动接线不适用于非弹簧Singleton

时间:2019-10-24 16:25:26

标签: java spring autowired

我有非弹簧public class MySingleton,它具有通过Spring注入的MyBattis Mapper,如下所示:

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;
    }
}

myMapper从未初始化,在构造函数中始终为null。我已经测试过在我的Singleton之前声明并创建了该bean,我也尝试了Configurable注释,但没有任何效果。

有人可以帮助我吗?

4 个答案:

答案 0 :(得分:1)

要检索非托管类上的托管Spring bean,我编写了一个类,它可以完成您想做的事情。

@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);
    }
}

要获取托管bean,只需ApplicationContextProvider.getBean(MyMapper.class);

答案 1 :(得分:0)

您可以在非托管类中实现ApplicationContextAware接口。这将导致通过设置器注入应用程序上下文,并允许您访问Spring生态系统的其余部分。

然后,您可以致电applicationContext.getBean(MyMapper.class);

答案 2 :(得分:-1)

注释MyMapper类@Component注释。这意味着当使用基于注释的配置和类路径扫描时,Spring框架将自动检测这些类以进行依赖项注入。

答案 3 :(得分:-1)

MyMapper此类未在IOC中注册为Bean。首先使用@Component或XML文件将MyMapper类注册为bean,然后运行