将自定义配置写在配置文件中
修改配置文件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

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

被折叠的 条评论
为什么被折叠?



