有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我不熟悉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) 个答案

  1. # 1 楼答案

    spring不知道如何在Animal构造函数中构建Cat对象,您还需要为spring定义一个默认构造函数

    您还可以@AutowiredAnimal类中的Cat,spring将知道如何构建Animal(就像您在测试类中所做的那样),在这种情况下,构造函数是不必要的

    public class Animal {
        @Autowired
        private Cat cat;
    
        public Cat getCat() {
            return cat;
        }
    ....