application.yml的内容注入到Bean

1. 待注入的application.yml内容 (部分内容)

coupon:
  sale: 
    name: 满100减10元
    amount: 100
    discount: 10

2. 组件

package com.discount.config;

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


@Component
@Data
@ConfigurationProperties(prefix = "coupon.sale")
public class Coupon {
    private String name;
    private float amount;
    private float discount;
}

3. 控制器

package com.discount.demo1;

import com.discount.config.Coupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class Demo1 {
    @Autowired
    private Coupon coupon;

    @RequestMapping("/discount/coupon")
    public String getCoupon() {
        String couponName = coupon.getName();
        float amount = coupon.getAmount();
        float discount = coupon.getDiscount();
        return "couponName:" + couponName + ",discount:" + discount + ",amount:" + amount;
    }
}

 

showtooltip

上一篇:量化交易测试笔记


下一篇:2021-02-06