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

时间:2015-03-19 14:01:24

标签: java spring jpa

我试图设置一些额外的属性Spring MVC应用程序Java - 配置样式。在这种情况下,我想设置spring.jpa.show-sql = true

在我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;
   }

我的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

我发现的所有教程都教我如何通过xml配置额外的道具。如何通过Properties方法获取此属性或任何其他属性?

修改

不是解决方案,但是使用setProperties()手动设置属性并且我的SQL显示

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

1 个答案:

答案 0 :(得分:0)

您是否定义了PropertySourcePlaceholderConfigurer bean?我很确定使用@PropertySource是必要的。如果您这样做,请尝试将@PropertySource值设置为classpath:/application.properties(请注意前导/)