其他分享
首页 > 其他分享> > application.yml的内容注入到Bean

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

标签:discount,coupon,amount,springframework,application,Bean,org,import,yml
来源: https://www.cnblogs.com/coding8832/p/14466645.html