简体   繁体   English

使用Java配置在Spring JPA中设置其他属性

[英]Setting Additional Properties in Spring JPA with Java Configuration

I'm trying to set some extra properties Spring MVC application Java - config style. 我正在尝试设置Spring MVC应用程序Java的一些额外属性-配置样式。 In this case, I want to set spring.jpa.show-sql = true 在这种情况下,我想设置spring.jpa.show-sql = true

In my PersistenceJPAConfig.java I have the following: 在我的PersistenceJPAConfig.java我具有以下内容:

@PropertySource("classpath:application.properties")
//other annotated configurations
public class PersistenceJPAConfig{

@Autowired
private Environment environment;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "com.banks.myapp" });
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties()); //fetches the properties
        return em;
}
@Bean
public DataSource dataSource(){ //All datasource properties are retrieved fine
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName(environment.getRequiredProperty("spring.datasource.driverClassName"));
      //set password, username, etc.
      return dataSource;
}

 Properties additionalProperties() {
      Properties properties = new Properties();
      properties.getProperty("spring.jpa.show-sql");//not fetching/setting property
      return properties;
   }

And my application.properties: 和我的application.properties:

spring.datasource.url=jdbc:jtds:sqlserver://mydatabase.com:5555/db
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driverClassName=net.sourceforge.jtds.jdbc.Driver
spring.jpa.show-sql: true

All the tutorials I've found teach me how to configure extra props via xml. 我发现的所有教程都教我如何通过xml配置额外的道具。 How can I grab this or any additional properties via the Properties method? 如何通过Properties方法获取此属性或任何其他属性?

EDIT 编辑

Not a solution, but setting the property manually with setProperties() works and my SQL is shown 不是解决方案,但是可以使用setProperties()手动设置属性,并且显示我的SQL

 properties.setProperty("spring.jpa.show-sql", "true");

Do you have a PropertySourcePlaceholderConfigurer bean defined? 您是否定义了PropertySourcePlaceholderConfigurer bean? I'm pretty sure that's necessary for using the @PropertySource . 我很确定使用@PropertySource是必需的。 If you do, try setting the @PropertySource value to classpath:/application.properties (note the leading /) 如果这样做,请尝试将@PropertySource值设置为classpath:/application.properties (注意classpath:/application.properties的/)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM