簡體   English   中英

執行 @Bean 注解的方法時,自動裝配的環境變量為 NULL

[英]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 文件(或其他文件格式)獲取數據有不同/更好的方法,我願意嘗試。

有很多方法可以做到這一點。

  1. 由於您使用的是 Springboot,因此您不必像這樣顯式創建數據源。 如果您使用右鍵聲明 properties/yml 中的參數,Springboot 會為您自動配置。
    搜索spring.datasource...... 在這里

  2. 如果您希望自己執行此操作,則可以使用ConfigurationProperties將 properties/yml 文件中的所有變量自動連接到 Bean 中,然后將此 bean 用作 bean 創建方法中的方法參數。
    看看這個

  3. 在您的 AppConfig class 中使用@Value{}並在您的數據源創建方法中使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM