Using JPA repository access in constructor of Service class

半世苍凉 提交于 2021-01-29 05:25:44

问题


I have spring boot app with a service (annotated @Service) and having several JPA repository interfaces.

Now I want to read entries form a database during the start of the service cause the JPA repository and the database connection is done before anything else.

So I have decided to put that code into the constructor of the service.

The question is:

  • Is this a correct way to initialise some attributes of a service only once at the start of the application (configuration which is stored in database)?

  • I have taken a look at @PostConstruct and InitializingBean interface (but they make it hard to write a test for them ? (Maybe I overlooked something here?) is this a better way?

Update I The service for configuration only contains an injection (via constructor) of a single JPA repository (table which contains the configuration parts). within the constructor only a few values will be read from the database (at the moment 4) and assigned to attributes of the service. (I have simplified that a little bit and drilled it down to the most important parts here):

@Service
public class ConfigService {
  private final ConfigRepository configRepository;

  private final Duration configValueOne;

  public ConfigService(ConfigRepository configRepository) {
    this.configValueOne=convertFromRepoToDuration("ATTRIBUTE");
  }

  public Duration configValueOne() {
    return configValueOne;        
  }

}

Update II:

  • The configuration will be used in several areas of the application that's the reason I have implemented that as a service.
  • A change of the values in the db will take only effect after a restart of the application which is exactly intended that way.

来源:https://stackoverflow.com/questions/62679679/using-jpa-repository-access-in-constructor-of-service-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!