【问题标题】:Spring junit autowired custom class must have constructor itself?Spring junit自动装配的自定义类必须有构造函数本身?
【发布时间】:2018-03-26 08:15:10
【问题描述】:

我是 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. 如果需要构造函数,为什么?

【问题讨论】:

    标签: java spring junit constructor autowired


    【解决方案1】:

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

    你也可以@AutowiredCatAnimal类中,并且spring会知道如何构建Animal(就像你在测试类中所做的那样)在这种情况下构造函数不是必需的

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

    【讨论】:

    • 谢谢!但是当我将 Cat 更改为 List 时它不起作用。我的 yaml 文件现在看起来像这样:动物:猫:-腿:四-腿:三
    猜你喜欢
    • 2016-10-10
    • 2012-05-06
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    相关资源
    最近更新 更多