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