更改@Autowired
(@Resource
来自 javax.annotation)并使其public
例如:
@Configuration
@PropertySource("classpath:database.properties")
public class HibernateConfigurer {
@Resource
public Environment env;
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("database.driverClassName"));
dataSource.setUrl(env.getProperty("database.url"));
dataSource.setUsername(env.getProperty("database.username"));
dataSource.setPassword(env.getProperty("database.password"));
dataSource.setValidationQuery(env.getProperty("database.validationQuery"));
return dataSource;
}
}
而且您必须以这种方式在 WebApplicationInitializer 中注册您的配置器类
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ApplicationConfigurer.class); //ApplicationConfigurer imports HibernateConfigurer
它对我有用!您可能想检查我制作的测试项目。