Home > Net >  How to access configuration beans in Spring controllers
How to access configuration beans in Spring controllers

Time:10-15

I have a Spring Boot application that uses Spring profiles to create environment specific configurations, for example:

@Configuration
@Profile("local")
public class LocalConfiguration
...

@Configuration
@Profile("prod")
public class ProdConfiguration
...

I have a @RestContoller that needs to access the values that the configurations load from application.properties. How can I inject the current environment specific configuration bean inside the controller?

Example:

@Autowired
private <config_based_on_env_here> config;

@RestController
public String getSomeString() {
    return config.getSomeString();
}

CodePudding user response:

If you need to access values from the application.properties or .yaml configuration you could use a much simpler way for achieving this.

Firstly configure different configs:

application-local.properties

my.value=local-value

application-prod.properties

my.value=prod-value

Create a configuration for reading needed value:

@Configuration
@ConfigurationProperties(prefix = "my")
public class ConfigProperties {
    
    private String value;

    // standard getters and setters
}

Finally, you could autowire this configuration at the controller:

@RestController
class MyController {

    @Autowire
    private ConfigProperties config;

    @GetMapping("/hello")
    public void hello() {
      System.out.println("Config value: "   config.getValue()); 
    }
}

Also, you could have a look at @Value annotation

Additional resources:

CodePudding user response:

Spring keeps your configuration-based properties in an instance of the Environment class. If you keep your properties in files named application-local.properties and application-prod.properties you don't need to explicitly declare the beans as you have shown. Spring will pick the correct properties file based on the profile that is active. Inject the environment as follows:

@Autowired
private Environment config;
  • Related