我有这个存储库类,我希望在单元测试中 Autowiring 它。目前,我在运行测试时收到“无默认构造函数”错误。
有问题的类没有默认构造函数,我是 spring 新手,所以可能没有在配置类中正确创建 Bean。
下面是有问题的 Bean(没有默认构造函数)
@Repository
public class GenericDaoImpl<T extends AbstractEntity> implements GenericDao<T> {
配置类
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.example")
public class AppConfig {
@Bean
GenericDaoImpl<AbstractEntity> genericDoaIpm(final Class<AbstractEntity> tClass) {
return new GenericDaoImpl<AbstractEntity>(tClass);
}
}
在测试中我有:
@Autowired
private GenericDaoImpl<AbstractEntity> genericDaoImpl;
我在这里遗漏或做错了什么吗?
最佳答案
根据this和 this ,你只需要用 @Autowired
标记你的构造函数。
GenericDaoImpl.java
@Autowired
public GenericDaoImpl(Class<?> tClass) {
...
}
You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no elements are used while configuring the bean in XML file
关于java - 没有默认构造函数的 Autowire Bean,使用配置注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26422511/