Spring junit autowired自定义类必须有构造函数本身吗?

时间:2018-03-26 08:15:11

标签: java spring junit constructor autowired

我是Spring框架的新手。我在尝试编写spring集成测试时遇到了一个问题。

我得到了这个动物类。

@Configuration
@ConfigurationProperties(prefix = "animal")
public class Animal {
    private Cat cat;

    /*public Animal(Cat cat) {
        this.cat = cat;
    }*/

    public Cat getCat() {
        return cat;
    }

    public static class Cat {

        @Value("${leg}")
        private String leg;

        public String getLeg() {
            return leg;
        }
    } 
}

我的集成测试

@RunWith(SpringRunner.class)
@EnableConfigurationProperties
@TestPropertySource("classpath:../classes/conf/animal.yml")
@ContextConfiguration(classes={Animal.class, Animal.Cat.class})

public class AnimalTest {

    @Autowired
    Animal animal;

    @Test
    public void testAnimal(){
        System.out.println("animal.cat.leg : " + animal.getCat().getLeg());
        Assert.assertEquals("four", animal.getCat().getLeg());
    }
}

这是我的yaml文件内容

animal:
    cat: 
        leg: four

我收到此错误,哪个spring框架无法正确读取我的yaml文件内容。

java.lang.NullPointerException: null
    at com.openet.tsb.AnimalTest.testAnimal(AnimalTest.java:41)

在我取消注释我的Animal构造函数后,测试将通过。

所以我的问题是,

  1. 构造函数是必要的吗?
  2. 是否有另一种方法可以跳过构造函数并自动将变量名称匹配到yaml文件中的名称?
  3. 如果需要构造函数,为什么?

1 个答案:

答案 0 :(得分:0)

spring不知道在Cat构造函数中构建Animal对象的位置和方式,还需要定义spring的默认构造函数

你也可以@Autowired Cat类中的Animal和spring将知道如何构建Animal(就像你在测试类中所做的那样)在这种情况下构造函数没有必要

public class Animal {
    @Autowired
    private Cat cat;

    public Cat getCat() {
        return cat;
    }
....