@value值获取不到配置文件值

(测试发现${employee.username}所在类必须要注入(放在controller、service、compnent…下)并且@test 或者new 对象获取不到值)

package com.it.sm2.signsm;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
//springboot 读取配置第一种方式
@Component
@Data
public class Employee {
    @Value("${employee.username}")
    private String username;
    @Value("${employee.password}")
    private Long password;
    @Value("${employee.age}")
    private Integer age;
}
package com.it.sm2.signsm;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
//springboot 读取配置第二种方式
@Component
@ConfigurationProperties(prefix = "department")
@Data
public class Department {
    private String username;
    private Long password;
    private Integer age;
}
package com.it.sm2.signsm;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class FirstController {

    @Value("${employee.username}")
    private String username;
    @Value("${employee.password}")
    private Long password;

    @Autowired
    private  Employee se;

    @RequestMapping("/")
    @ResponseBody
    String home()
    {
        return "Hello Springboot!";
    }

    @RequestMapping("/hello")
    @ResponseBody
    String hello()
    {
        //测试new 是否可以获取@value;只能使用注入
//        Employee e = new Employee();
        String ss =se.getUsername();
        return "username: " + username + ", " + "password: " + password+ss;
    }
    //test不能获取到值,@value 是获取的容器的配置值
    @Test
    public void s(){
        System.out.println(this.password);
    }
}
department.username= ddd
department.password: 222
department.age: 22

employee.username=sss
employee.password=111
employee.age=11
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

健身小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值