Reputation: 35
In the main controller, I am able to read the properties. If I have a properties class and try to access these or inject the below values in every class that requires the properties I am unable to do so. what is missing? I do not want to pass around variables to all the functions from the main controller.
@SpringBootApplication
@Configuration
public class ApplicationProperties {
@Autowired
@Value("${file.location}")
private String fileLocation;
@Value("${file.name}")
private String fileName;
/**
* @return the fileLocation
*/
@RequestMapping(value="/")
public String getFileLocation() {
return fileLocation;
}
/**
* @return the fileName
*/
@RequestMapping(value="file")
public String getFileName() {
return fileName;
}
}
Upvotes: 0
Views: 2369
Reputation: 4414
The simplest approach may be:
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
@Component
public class MyBean {
@Value("${file.location}")
private String fileLocation;
@Value("${file.name}")
private String fileName;
// ...
}
Spring will load properties from application.properties by default.
Or you can use specify a different file name in a configuration class using @PropertySource:
package com.my.config;
//.. spring imports
@Configuration
@ComponentScan(basePackages = { "com.my.config" })
@PropertySource("classpath:config.properties")
public class MyConfigClass {
@Value("${project.name:Default Project Name}")
private String projectName;
// giving fileName a default value in case the one specified doesn't exist
@Value("${file.name:defaultfile.txt}")
private String fileName;
//...
}
See info on Spring Boot externalized configuration here.
Upvotes: 0
Reputation: 221
First of all you don't need the annotation @SpringBootApplication unless the class has main method.
Secondly, you don't need the annotation @Autowired on fileLocation because @Value is sufficient.
Finally, you need the annotation @RestController because it's a REST api.
Now:
Either add main method to you class and omit @configuration otherwise you need to create a main class with the annotation @SpringBootApplication and keep @RestController.
Upvotes: 1