程序猿的幽默

@Component 无法注入Bean ,无法使用 @value

2022-04-24  本文已影响0人  赵优秀

一. 原因是 spring容器加载bean时机不同,导致注入bean为空

参考1: https://www.cnblogs.com/DF-Kyun/p/12669095.html

1). 依赖注入

这里通过另外一种方式解决,通过ApplicationContextAware接口的方式获取ApplicationContext对象实例

@Component
public class MyListener implements TaskListener, ApplicationContextAware {

    private static  ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }

    @Override
    public void notify(DelegateTask delegateTask) {

        String processInsId = delegateTask.getProcessInstanceId();
        MyService myService = (MyService) applicationContext.getBean("myService");

        // TODO 执行service方法
        
        System.out.println("==========执行监听器======");
    }

}

2). SpringContextUtils

直接获取Bean

SpringContextUtils.getBean(RepositoryService.class)

@Value 获取值

SpringContextUtils.getApplicationContext().getEnvironment().getProperty("xx.xx.xx")

二. 不用@Value从Spring的ApplicationContext中获取一个或全部配置

参考2: https://www.bbsmax.com/A/kvJ3vybwzg/

获取配置

applicationContext.getEnvironment().resolvePlaceholders("${propertyKey}"); // 方法1
applicationContext.getEnvironment().getProperty("propertyKey"); // 方法2

获取properties配置文件的配置:

ConfigurableEnvironment env = (ConfigurableEnvironment) applicationContext.getEnvironment();
MutablePropertySources propertySources = env.getPropertySources();
Iterator<PropertySource<?>> iterator = propertySources.iterator();
while (iterator.hasNext()) {
    PropertySource<?> propertySource = iterator.next();
    if (propertySource instanceof PropertiesPropertySource) {
        System.out.println(propertySource.getProperty("propertyKey"));
        // 用propertySource.getSource()  可以获取全部配置
    }
}

正常实现EnvironmentAware, 即可让spring容器自动注入Environment

上一篇下一篇

猜你喜欢

热点阅读