@Component 无法注入Bean ,无法使用 @value注解问题

一. 原因是 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容