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

Posted 健身小白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@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

以上是关于@value值获取不到配置文件值的主要内容,如果未能解决你的问题,请参考以下文章

解决Spring 使用 @Value 取不到值

yml $的用法

react使用antd中input获取value值获取不到

@value注解获取属性文件的值怎么转换成int类型

SpringBoot通过@Value获取application.yml配置文件的属性值

在controller中无法通过注解@Value获取到配置文件中定义的值解决办法