如何在休眠配置中修复NPE?

时间:2019-09-09 10:29:57

标签: java spring hibernate

@Autowired Environment env-始终为null。这是我的HibernateConf.java:

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:hibernate.properties" })
public class HibernateConf{

    @Autowired
    private Environment env;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[]{"Enteties"});
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("com.mysql.cj.jdbc.Driver")));
        dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc:mysql://localhost:3306/tutorialdb?createDatabaseIfNotExist=true")));
        dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("root")));
        dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("9339")));
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager hibernateTransactionManager() {
        final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }

    private final Properties hibernateProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("create-drop"));
        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("org.hibernate.dialect.MySQL5Dialect"));

        return hibernateProperties;
    }
}

所以主要的问题是这个@Autowired private Environment env;总是NPE,但我不知道为什么,因为此配置类的每个示例都与我的相同。我该如何解决?

1 个答案:

答案 0 :(得分:0)

(代表问题作者发布,将其从问题移至答案空间)

我找到了解决此问题的方法。首先,您需要删除@Autowired private Environment env;,然后dataSource.setPassword("9339")仅将其与String参数一起使用。

第三,您需要的不是5.0 ... mysql-connector而不是4.0 ...而是这个:

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.17</version>
</dependency>