I had a hard time not knowing how to refer to the property file in Spring Boot, so I wrote it as an article. I think that you can understand it if you have enough knowledge to "Hello World" with Spring Boot.
Prepare the property file in src / main / resources through the classpath. The name of the property file can be anything.
hogeConfig.properties
hoge.foo=foooooooo
hoge.bar=barrrrrrr
Add @Component to make it a Bean (a class that can be Autowired). Specify the name of the property file with @PropertySource. Specify the property prefix with @ConfigurationProperties. Describe variables, setters and getters.
HogeConfig.java
@Component
@PropertySource("classpath:hogeConfig.properties")
@ConfigurationProperties(prefix = "hoge")
public class HogeConfig {
private String foo;
//setter getter omitted
}
Prepare the Controller and Service classes. Inject the bean prepared earlier with @Autowired. Call the getter of the injected bean.
HogeController.java
@RestController
public class HogeController {
@Autowired
private HogeConfig hogeConfig;
@GetMapping("/hoge")
public String hoge() {
return hogeConfig.getFoo(); // foooooooo
}
}
Spring @PropertySource example Type-safe property settings in @ConfigurationProperties of Spring Boot Why Spring recommends Constructor Injection over Field Injection
Recommended Posts