简体   繁体   中英

Setting Additional Properties in Spring JPA with Java Configuration

I'm trying to set some extra properties Spring MVC application Java - config style. In this case, I want to set spring.jpa.show-sql = true

In my PersistenceJPAConfig.java I have the following:

@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:

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. How can I grab this or any additional properties via the Properties method?

EDIT

Not a solution, but setting the property manually with setProperties() works and my SQL is shown

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

Do you have a PropertySourcePlaceholderConfigurer bean defined? I'm pretty sure that's necessary for using the @PropertySource . If you do, try setting the @PropertySource value to classpath:/application.properties (note the leading /)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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