我试图在任何数据库操作之前验证查询,如果数据库连接失败,应该重新连接选项而不在数据源代码中添加属性工作正常。
以下是我的代码
@Configuration
@EnableTransactionManagement
@PropertySource({"classpath:application.properties"})
public class DatabaseConfig {
@Value("${db.driver}")
private String DB_DRIVER;
@Value("${db.password}")
private String DB_PASSWORD;
@Value("${db.url}")
private String DB_URL;
@Value("${db.username}")
private String DB_USERNAME;
@Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
@Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
@Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
@Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// DataSource dataSource = new DriverManagerDataSource();
// org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
Properties configProps = new Properties();
configProps.put("db.validationQuery", "SELECT 1");
configProps.put("db.testOnBorrow", true);
configProps.put("testWhileIdle", true);
dataSource.setConnectionProperties(configProps);
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
但它给了我错误
o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adminDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [com/ehydromet/dao/impl/DatabaseConfig.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException