springboot2.x 3.2.自定义配置

本文介绍如何在SpringBoot项目中使用YAML配置文件进行自定义配置,并通过@Value注解将配置项注入到Service层。同时展示了如何在Controller中通过@Resource注解调用Service方法,实现对配置信息的读取。
将自定义配置写在配置文件中

修改配置文件application.yml

server:
  port: 10080

myconfig:
  config1: "1"
  config2: "2"
用 @Value注解注入配置

DemoService

package com.imsjw.demo.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class DemoService {

    @Value("${myconfig.config1}")
    private String myconfig1;
    @Value("${myconfig.config2}")
    private String myconfig2;

    public String testConfig() {
        return myconfig1 + myconfig2;
    }

}

DemoController
@Resource 注解注入Service (单例模式)

package com.imsjw.demo.controller;

import com.imsjw.demo.service.DemoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private DemoService demoService;

    @ResponseBody
    @RequestMapping("/test")
    public String test(){
        return demoService.testConfig();
    }

}
测试
http://127.0.0.1:10080/demo/test
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小萨技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值