java spring@autowire在测试类中不工作

lndjwyie  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(344)

这个问题在这里已经有了答案

为什么自动连接spring存储库不起作用(1个答案)
三个月前关门了。
我有一个自动连接catalogdao类的测试类。但是catalogdao类不是自动连接的。值为空;
测试等级

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = {PersistenceConfig.class})
  3. public class CatalogDaoIT {
  4. @Autowired
  5. private CatalogDao catalogDao;
  6. @Test
  7. public void saveCatalog_readSame_foundOne() {
  8. // arrange
  9. Catalog catalog = new Catalog();

配置类

  1. package ch.matica.platform.persistence.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.PropertySource;
  6. import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
  7. @Configuration
  8. @PropertySource("classpath:application.properties")
  9. @ComponentScan(basePackages = "ch.matica.platform.persistence")
  10. public class PersistenceConfig {
  11. @Bean
  12. public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
  13. return new PropertySourcesPlaceholderConfigurer();
  14. }
  15. }

道类

  1. package ch.matica.platform.persistence;
  2. import java.util.Collection;
  3. ...
  4. @Repository
  5. public class CatalogDao {
  6. ...
nnt7mjpx

nnt7mjpx1#

你能把代码改成这样吗:

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = {PersistenceConfig.class})
  3. public class CatalogDaoIT {
  4. @Autowired
  5. private CatalogDao catalogDao;
  6. //autowire by type, a private field and a setter
  7. @Autowired
  8. public void setCatalogDao(CatalogDao cd){
  9. this.catalogDao=cd;
  10. }
  11. @Test
  12. public void saveCatalog_readSame_foundOne() {
  13. // arrange
  14. Catalog catalog = new Catalog();

我想这会有帮助的。

展开查看全部
nafvub8i

nafvub8i2#

对我来说这很管用

  1. @SpringBootTest
  2. public class CatalogDaoIT {
  3. ....
  4. }

相关问题