yml属性注入

1、定义对象

package com.wbb.entity;

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

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author worker
 * @package porjects-com.wbb
 * @create 2021 - 07 - 19 - 15:55
 */
@Component
@ConfigurationProperties(prefix = "myuser")
public class User {
    private Integer id;
    private String name;
    private Date birthday;
    private BigDecimal salary;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                ", salary=" + salary +
                '}';
    }
}

  2、配置文件配置属性值

myuser:
  id: 22
  name: baobao
  birthday: 1994/05/05
  salary: 9999

  

  3、使用

  

package com.wbb.controller;

import com.wbb.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author worker
 * @package porjects-com.wbb.controller
 * @create 2021 - 07 - 19 - 15:33
 * 属性注入
 */
@RestController
public class InjectController {

    private User user; 

    @RequestMapping("/injectObject")
    public String injectObject(){
        System.out.println(user.toString());
        return "inject ok~~~"+user.toString();
    }

    @Autowired
    public void setUser(User user) {
        this.user = user;
    }
}

如果有报错,引入依赖构建自定义注入元数据,然后重启

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

 注意: 若前缀使用的是user,user.name会查找 本机电脑名。。。。。。避免吧

 

以上是对象注入,若基本数据类型注入

1、配置文件配置属性值  xxx.yml

name: zhangsan

2、使用属性,使用@value注解

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

 

posted @ 2021-07-19 16:15  neoQVQ  阅读(325)  评论(0)    收藏  举报