Spring boot(配置了@ConfigurationProperties但是输出值为空)

在上课的时候老师演示了使用注解来对类进行绑定,我实际操作起来确出了问题。

使用@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这个问题,原来竟然是这样子。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值