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

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

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

为什么自动连接spring存储库不起作用(1个答案)
三个月前关门了。
我有一个自动连接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();
        }
}

道类

package ch.matica.platform.persistence;

import java.util.Collection;
...

@Repository
public class CatalogDao {
...
nnt7mjpx

nnt7mjpx1#

你能把代码改成这样吗:

@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();

我想这会有帮助的。

nafvub8i

nafvub8i2#

对我来说这很管用

@SpringBootTest 
public class CatalogDaoIT {
....
}

相关问题