简体   繁体   中英

Autowired Environment variable is NULL when @Bean annotated method is executed

I'm attempting to retrieve properties loaded from a.yml file by autowiring an Environment variable, but I'm getting a null pointer exception:

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

I want to programatically create a DataSource bean while keeping the details (username, password, host, etc) in a configuration file. This is my setup at the moment:

@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();
  }
}

I'm not partial to either the.yml file format or using the Environment variable. If there is a different/better way to go about getting the data from the.yml file (or some other file format), I'm willing to try it.

There are many ways to do this.

  1. Since you are using Springboot, you do not have to create a Datasource explicitly like this. If you declare the parameters in properties/yml with right keys, Springboot with Autoconfigure this for you.
    Search for spring.datasource...... here

  2. If you wish to do this on your own, then You can autowire all the variables in properties/yml file into a Bean using ConfigurationProperties then use this bean as method parameter in your bean creation method.
    check this out

  3. Use @Value{} in your AppConfig class and use it in your Datasource creation method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM