Spring Boot read values from application properties

abdoe :

I'm not sure if I understand it correctly, but from what I got, is that I can use @Value annotations to read values from my application.properties.

As I figured out this works only for Beans.

I defined such a bean like this

@Service
public class DBConfigBean {


    @Value("${spring.datasource.username}")
    private String userName;

    @Bean
    public String getName() {
        return this.userName;
    }
}

When the application starts I'm able to retrieve the username, however - how can I access this value at runtime?

Whenever I do

DBConfigBean conf = new DBConfigBean() conf.getName();

* EDIT *

Due to the comments I'm able to use this config DBConfigBean - but my initial problem still remains, when I want to use it in another class

@Configurable
public SomeOtherClass {

   @Autowired
   private DBConfigBean dbConfig; // IS NULL

   public void DoStuff() {
       // read the config value from dbConfig
   }
} 

How can I read the DBConfig in a some helper class which I can define as a bean

Thanks

Eirini Graonidou :

You shouldn't instantiate your service with the new operator. You should inject it, for example

@Autowired
private DBConfigBean dbConfig;

and then dbConfig.getName();

Also you don't need any @Bean decorator in your getName() method

You just need to tell spring where to search for your annotated beans. So in your configuration you could add the following:

@ComponentScan(basePackages = {"a.package.containing.the.service",
                             "another.package.containing.the.service"})

EDIT

The @Value, @Autowired etc annotations can only work with beans, that spring is aware of.

Declare your SomeOtherClass as a bean and add the package config in your @Configuration class

@Bean
private SomeOtherClass someOtherClass;

and then

 @Configuration
 @ComponentScan(basePackages = {"a.package.containing.the.service"              
  "some.other.class.package"})
 public class AppConfiguration {

  //By the way you can also define beans like:
   @Bean 
   public AwesomeService service() {
       return new AwesomeService();
   }

 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90459&siteId=1
Recommended