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"); } }
解决获取不到配置的问题