SpringBoot中通过@Value获取自定义配置的值
场景
在SpringBoot项目中的application.properties中定义变量,要在
controller中获取自定义配置的值。
实现
打开
application.properties
添加如下代码
book.author=Badao
book.name=SpringBoot
新建BookController.java
package com.example.demo.controller;
import javax.sound.midi.MidiDevice.Info;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableAutoConfiguration
@Controller
public class BookController {
@Value("${book.author}")
private String author;
@Value("${book.name}")
private String name;
@RequestMapping("/bookInfo")
@ResponseBody
public String showInfo() {
return author+":"+name;
}
public static void main(String[] args) {
SpringApplication.run(BookController.class, args);
}
}
右键run as --java application
效果
打开浏览器输入:
http://localhost:8080/bookInfo