Patrick
Patrick

Reputation: 3

SpringBoot get environment variables for @Configuration class

I'm struggling with the following problem:

In my springboot project I want to initialize a datasource by myself. Inside that method I want to work with some environment variables which I read from a YML file.

@Configuration
public class DataSourceConfig {
    @Bean
    public JdbcDataSource createMainDataSource() {
        // init datasource and read some environment variables
    }
}

Application.yml:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/XXX
    driverClassName: com.mysql.jdbc.Driver

Then I defined another class with @Configuration where I obtain the environment variables.

@Configuration
@ConfigurationProperties(prefix="spring.datasource")
public class PropertiesConfig {

    private String url;

    private String driverClassName;
}

But now I have the problem that the class DataSourceConfig is being initialized before PropertiesConfig leading to the problem that I can't use the environment variables.

Can somebody of you help me with that?

Upvotes: 0

Views: 1635

Answers (1)

Roland Weisleder
Roland Weisleder

Reputation: 10511

To create your DataSource you need your PropertiesConfig, so just inject it into your bean:

@Configuration
public class DataSourceConfig {

    @Autowired
    private PropertiesConfig propertiesConfig;

    @Bean
    public JdbcDataSource createMainDataSource() {
        // init datasource and read some environment variables
    }
}

Upvotes: 2

Related Questions