I want to use properties from application.properties file. Before I was using
@Value({"valueFromProperties}
annotation but I would like to change it on @ConfigurationProperties annotation. I prepared some app with TestController:
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {
private final TestService testService;
@GetMapping
public String test() {
return testService.test();
}
}
in TestService I have only test method (access to repostitory becouse I will work with database later) and getters / setters for that fields.
@Service
@RequiredArgsConstructor
public class TestService {
private final TicketEntityRepository ticketEntityRepository;
private String hostName;
private int port;
private String from;
public String test(){
return getHostName() + " " + getPort() + " " + getFrom();
}
and now it work, but is any other way to inject that properties by constructor?
EDIT: Ok, so I changed a little... In my configuration class I added bean:
@PropertySource(value = {"classpath:testconfig.properties"})
public class Config implements WebMvcConfigurer {
@Bean
@ConfigurationProperties
public TestProperties testConfig() {
return new TestProperties();
}
TestProperties class has only fields like in properties:
@Data
public class TestProperties {
private String hostName;
private int port;
private String from;
}
and now my Service looks like:
@Service
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "test")
public class TestService {
private final TicketEntityRepository ticketEntityRepository;
private final TestProperties testProperties;
public String test(){
return testProperties.getHostName() + " " + testProperties.getPort() + " " + testProperties.getFrom();
}
}
Will be better now?