首页 > 解决方案 > 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 {
...

标签: javaspringautowired

解决方案


对我来说这有效

@SpringBootTest 
public class CatalogDaoIT {
....
}

推荐阅读