繁体   English   中英

没有默认构造函数的Autowire Bean,使用config批注

[英]Autowire Bean with no default constructor, using config annotation

我有这个Repository类,希望在单元测试中自动连线。 我目前在运行测试时遇到“没有默认构造函数”错误。

有问题的类没有默认的构造函数,我是spring的新手,所以可能没有在config类中正确创建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;

我有什么想念的地方吗?

根据 一点 ,您只需要用@Autowired标记您的构造函数。

GenericDaoImpl.java

@Autowired
public GenericDaoImpl(Class<?> tClass) {
    ...
}

您也可以将@Autowired应用于构造函数。 构造函数@Autowired批注指示即使在XML文件中配置Bean时不使用任何元素,也应在创建Bean时自动构造该构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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