其他分享
首页 > 其他分享> > SpringBoot/Spring使用@Value进行属性绑定(传智播客代码)

SpringBoot/Spring使用@Value进行属性绑定(传智播客代码)

作者:互联网

接上篇:

部分代码参考上篇,这里用@Value读取值

@Value支持字面量、Spring EL表达式(#),美元符号($),相比于@ConfigurationProperties,他用$取值时需要完全路径

package com.atguigu.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Person {

    /***
     * 美元表达式(从配置文件、系统环境变量读取)
     */
    @Value("${person.lastName}")
    private String lastName;

    /***
     * Spring EL表达式
     */
    @Value("#{11*2}")
    private Integer age;

    /***
     * 字面量
     */ 
    @Value("true")
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
}

 

 

 

 

ConfigurationProperties注解JSR303数据校验
package com.atguigu.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    @Email
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
}

由于lastName不是有效的邮箱,启动时即报错

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'person' to com.atguigu.bean.Person failed:

    Property: person.lastName
    Value: zhangsan
    Origin: class path resource [application.properties]:2:17
    Reason: 不是一个合法的电子邮件地址

 

标签:传智播,SpringBoot,Spring,springframework,Value,util,private,import,lombok
来源: https://www.cnblogs.com/passedbylove/p/12639020.html