Spring JPA:无法通过属性文件配置外部数据库

时间:2019-10-04 19:34:07

标签: java spring properties spring-data-jpa spring-data

我想使用外部属性文件来加载数据库和REST端点信息。我试图避免使用XML配置,而倾向于基于注释的配置。

我创建了两个类,两个类都用@Configuration进行了注释,并在其构造函数中使用了@Value注释来加载属性:

RestConfiguration.java

@Configuration
public class RestConfiguration {
  private final String grantType;
  private final AuthenticationScheme authenticationScheme;
  private final String clientId;
  private final String clientSecret;
  private final String accessTokenUri;

  private final boolean useProxy;
  private final String proxyHost;
  private final int proxyPort;

  @Autowired
  public RestConfiguration(
      @Value("${api.oauth2.grant-type}") String grantType,
      @Value("${api.oauth2.authentication-scheme}") AuthenticationScheme authenticationScheme,
      @Value("${api.oauth2.client-id}") String clientId,
      @Value("${api.oauth2.client-secret}") String clientSecret,
      @Value("${api.oauth2.url}") String accessTokenUri,
      @Value("${net.proxy}") boolean useProxy,
      @Value("${net.proxy.host}") String proxyHost,
      @Value("${net.proxy.port}") int proxyPort) {
    this.grantType = grantType;
    this.authenticationScheme = authenticationScheme;
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.accessTokenUri = accessTokenUri;
    this.useProxy = useProxy;
    this.proxyHost = proxyHost;
    this.proxyPort = proxyPort;
  } 
}

PersistenceConfiguration.java

@Configuration
public class PersistenceConfiguration {
  private final String host;
  private final String port;
  private final String database;
  private final String schema;
  private final String user;
  private final String password;

  @Autowired
  public PersistenceConfiguration(
      @Value("${db.host}") String host,
      @Value("${db.port}") String port,
      @Value("${db.database}") String database,
      @Value("${db.schema}") String schema,
      @Value("${db.user}") String user,
      @Value("${db.password}") String password) {
    this.host = host;
    this.port = port;
    this.database = database;
    this.schema = schema;
    this.user = user;
    this.password = password;
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan("ch.example.rest.entities");

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
  }

  @Bean
  public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUrl("jdbc:postgresql://" + host + ":" + port + "/" + database);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setSchema(schema);
    return dataSource;
  }

  @Bean
  public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
  }

  Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "none");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL95Dialect");
    properties.setProperty(
        "hibernate.physical_naming_strategy",
        "ch.example.rest.configurations.SnakeCaseNamingStrategy");
    properties.setProperty(
        "spring.datasource.hikari.data-source-properties", "stringtype=unspecified");

    return properties;
  }
}

两个配置文件都位于同一程序包(子程序包configurations)中。

初始化Spring上下文的类如下:

@Configuration
@ComponentScan(basePackages = "ch.example.rest")
@EnableJpaRepositories("ch.example.rest.repositories")
@PropertySource("classpath:application.properties")
public class RestClient {
    private CommandLineController commandLineController;

    @Autowired
    public RestClient(CommandLineController commandLineController) {
        this.commandLineController = commandLineController;
    }

    private static void main(String[] args) {
        // ... some parsing of command line arguments

        // Initialize context
        ApplicationContext ctx = new AnnotationConfigApplicationContext(RestClient.class);
        RestClient restClient = ctx.getBean(RestClient.class, uploadCommand);
        restClient.runCommand(parsedCommand, uploadCommand);
    }

    public void runCommand(String command, UploadBillsCommand uploadCommand) {
        // Some calls to a controller
        commandLineController....;
    }
}

有趣的是,RestConfiguration类接收属性,而PersistenceConfiguration不接收属性。在调试过程中,我注意到PersistenceConfiguration类几乎是立即构造的,而RestConfiguration是在稍后第一次调用RestTemplate时加载的。

我怀疑这可能与Spring JPA试图连接存储库并因此需要在启动时建立SQL连接这一事实有关。

我发现一个this问题,似乎表明如果没有其他样板代码,就无法在外部提供数据库配置。由于该问题已经存在5年了,所以我想知道是否存在另一个优雅的解决方案,无需创建第二个上下文即可解决此问题。

1 个答案:

答案 0 :(得分:1)

好的,答案似乎很简单。不必让Spring使用带有form_with批注的表达式语言来加载属性,我只需要注入action_params的实例,然后直接从中获取属性:

@Value