0

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?

Lulex97
  • 231
  • 1
  • 10
  • Don't please don't... That annotation is meant for objects that hold configuration not for services. Extract that information out of the service and make it a dedicated object. For that dedicated object if you want to use constructor injection add an additional `@ConstructorBinding` annotation to instruct the binding to use the constructor. – M. Deinum Sep 08 '22 at 12:34

0 Answers0