Spring junit autowired 自定义 class 必须有构造函数本身?
Spring junit autowired custom class must have constructor itself?
我是 Spring 框架的新手。我在尝试编写 spring 集成测试时遇到了问题。
我得到了这只动物 class。
@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 构造函数后,测试将通过。
所以我的问题是,
- 构造器有必要吗?
- 是否有另一种方法可以跳过构造函数并将变量名称匹配自动装配到 yaml 文件中的名称?
- 如果需要构造函数,为什么?
spring 不知道在 Animal
构造函数中在哪里以及如何构建 Cat
对象,您还需要为 spring[ 定义一个默认构造函数=17=]
你也可以@Autowired
Cat
里面的Animal
class和spring会知道如何构建Animal
(像你在测试中做了 class) 在这种情况下构造函数不是必需的
public class Animal {
@Autowired
private Cat cat;
public Cat getCat() {
return cat;
}
....
我是 Spring 框架的新手。我在尝试编写 spring 集成测试时遇到了问题。
我得到了这只动物 class。
@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 构造函数后,测试将通过。
所以我的问题是,
- 构造器有必要吗?
- 是否有另一种方法可以跳过构造函数并将变量名称匹配自动装配到 yaml 文件中的名称?
- 如果需要构造函数,为什么?
spring 不知道在 Animal
构造函数中在哪里以及如何构建 Cat
对象,您还需要为 spring[ 定义一个默认构造函数=17=]
你也可以@Autowired
Cat
里面的Animal
class和spring会知道如何构建Animal
(像你在测试中做了 class) 在这种情况下构造函数不是必需的
public class Animal {
@Autowired
private Cat cat;
public Cat getCat() {
return cat;
}
....