[英]Autowired Environment variable is NULL when @Bean annotated method is executed
我試圖通過自動裝配環境變量來檢索從 .yml 文件加載的屬性,但我得到了 null 指針異常:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/example/AppConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException
我想以編程方式創建一個 DataSource bean,同時將詳細信息(用戶名、密碼、主機等)保存在配置文件中。 這是我目前的設置:
@SpringBootApplication
@ImportResource({"classpath:controllers.xml"})
public class WebApplication{
public static void main(String[] args){
SpringApplication.run(WebApplication.class, args);
}
}
server:
port: 8080
database:
host: localhost
instance: db_instance
port: 3036
user: root
password: passkey
@Configuration
public class AppConfig {
@Autowired
private Environment environment;
@Bean
public DataSource dataSource() {
String url = "jdbc:mysql://" +
environment.getProperty("database.host") +
":" + environment.getProperty("database.port") +
"/" + environment.getProperty("database.instance") +
"?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true";
return DataSourceBuilder.create()
.driverClassName("com.mysql.jdbc.Driver")
.url(url)
.username(environment.getProperty("database.user"))
.password(environment.getProperty("database.password"))
.build();
}
}
我不偏愛 .yml 文件格式或使用環境變量。 如果 go 關於從 .yml 文件(或其他文件格式)獲取數據有不同/更好的方法,我願意嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.