在上课的时候老师演示了使用注解来对类进行绑定,我实际操作起来确出了问题。
使用@ConfigurationProperties来进行注解并在application.properties中进行了配置,但是输出并没有结果
文件结构、代码、运行截图如下
//实体类
package com.example.entity;
import com.example.entity.Dog;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myanimals")
public class Animals {
public String type;
public int age;
public Dog dog;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Animals{" +
"type='" + type + '\'' +
", age=" + age +
", dog=" + dog +
'}';
}
}
//application.properties中的配置
myanimals.type="CatScience"
myanimals.age=18
myanimals.dog='tiger'
//测试类中的代码
package com.example.configureset;
import com.example.entity.Animals;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ConfigureSetApplicationTests {
@Autowired
private Animals animals;
@Test
void Animalstest(){
System.out.println(animals);
}
}
这样你会得到一个结果:
而且在编写的过程中@Autowired下实例化的对象会变红
原因在于层级关系
这样animal这个类就在主类里,这是会发现而且在编写的过程中@Autowired下实例化的对象不变红了
代码什么都不用动而且结果如下:
网上查了很多的资料,发现无法解决@AutoWired这个问题,原来竟然是这样子。