@Value和@ConfigurationProperties

@ConfigurationProperties

1、通过两个注解即可批量注入文件属性

2、支持松散绑定(比如Properties中使用last-name,在.java文件中可以使用lastName驼峰命名法)

3、不支持SpEL表达式

4、支持JSP303数据校验

5、基本数据类型或者复杂数据类型都可以进行获取

@Value

1、每次都需要@Value指定。

2、字符串类型是$,数字类型是#

3、不支持松散绑定

4、支持SpEL表达式不支持JSP303数据校验

5、只能获取基本数据类型的,不能获取复杂类型的(map)

使用区别

1、如果只是业务逻辑代码简单使用一下配置文件中的值,就使用@Value。

2、当需要比较多的配置项,如果都是通过@Value的方式显得过于繁琐,此时就可以使用@ConfigurationProperties。

3、标有@ConfigurationProperties的类的所有属性和配置文件中相关的配置进行绑定。(默认从全局配置文件中获取配置值),绑定之后我们就可以通过这个类去访问全局配置文件中的属性值。

4、set方法一定要写,否则无法赋值。

application.properties

person.name=likeqin
person.age=99

方法一:@Value获取值

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Value("${person.name}")
    private String name;

    @Value("${person.age}")
    private int age;

    @GetMapping("/test")
    public JSONObject test() {
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("age", age);
        return json;
    }
}

方法二:@ConfigurationProperties获取值

Person.java

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 使用@Component才能使用容器提供的ConfigurationProperties功能
 * set方法是不可以缺少的,缺少了就不能设置name和age的值
 */
@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
    private String name;
    private Integer age;
}
import com.alibaba.fastjson.JSONObject;
import com.demo.mytest.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private Person p;

    @GetMapping("/test001")
    public JSONObject test001() {
        JSONObject json=new JSONObject();
        json.put("name", p.getName());
        json.put("age", p.getAge());
        return json;
    }
}

用到的pom.xml依赖

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.4</version>
</dependency>

<dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
     <optional>true</optional>
</dependency>
原文地址:https://www.cnblogs.com/YuRong3333/p/14526765.html