如何解决Java Spring @autowire 在测试类中不起作用
我有一个自动装配 CatalogDao 类的测试类。但是 CatalogDao 类不是自动装配的。值为空;
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class})
public class CatalogDaoIT {
@Autowired
private CatalogDao catalogDao;
@Test
public void saveCatalog_readSame_foundOne() {
// arrange
Catalog catalog = new Catalog();
配置类
package ch.matica.platform.persistence.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = "ch.matica.platform.persistence")
public class PersistenceConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}
DAO 类
package ch.matica.platform.persistence;
import java.util.Collection;
...
@Repository
public class CatalogDao {
...
解决方法
你能不能把你的代码改成这样:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class})
public class CatalogDaoIT {
@Autowired
private CatalogDao catalogDao;
//autowire by type,a private field and a setter
@Autowired
public void setCatalogDao(CatalogDao cd){
this.catalogDao=cd;
}
@Test
public void saveCatalog_readSame_foundOne() {
// arrange
Catalog catalog = new Catalog();
我认为这会有所帮助。
,对我来说这是有效的
@SpringBootTest
public class CatalogDaoIT {
....
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。