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

解决获取不到配置的问题

 

 

 

 





免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM