zoukankan      html  css  js  c++  java
  • SpringBoot在Configuration注解中使用@Value获取null的问题

    
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class MyConfigure {
        @Value( "${spring.application.name}")
        private  String name ;
    
        @Value( "${spring.datasource.driver-class-name}")
        protected String driverClassName ;
        
        public MyConfigure(){
            // 这里 name 和 driverClassName 都是null
        }
    }

    修改 MyConfigure 实现 EnvironmentAware 接口

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.env.Environment;
    
    @Configuration
    public class MyConfigure implements EnvironmentAware {
        @Value( "${spring.application.name}")
        private  String name ;
    
        @Value( "${spring.datasource.driver-class-name}")
        protected String driverClassName ;
        
        private Environment env;
    
        @Override
        public void setEnvironment(Environment environment) {
            this.env = environment; 
            this.doSomething();
        }
    
        public MyConfigure(){
            // 这里 name 和 driverClassName 都是null
        }
        
        private void doSomething(){
            // 这里 获取 name 和 driverClassName  
            this.driverClassName = this.env.getProperty("spring.datasource.driver-class-name");
        }
    }

    解决获取不到配置的问题




  • 相关阅读:
    bat脚本%cd%和%~dp0的区别
    java测试程序运行时间
    != 的注意事项
    [转载] iptables 防火墙设置
    .NET 创建 WebService
    [转载] 学会使用Web Service上(服务器端访问)~~~
    cygwin 安装 apt-cyg
    在Element节点上进行Xpath
    Element节点输出到System.out
    [转载] 使用StAX解析xml
  • 原文地址:https://www.cnblogs.com/Leechg/p/12331985.html
Copyright © 2011-2022 走看看