场景
在SpringBoot项目中的application.properties中定义变量,要在
controller中获取自定义配置的值。
实现
打开
application.properties
添加如下代码
book.author=Badaobook.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@Controllerpublic class BookController {@Value("${book.author}")private String author;@Value("${book.name}")private String name;@RequestMapping("/bookInfo")@ResponseBodypublic String showInfo() {return author+":"+name;}public static void main(String[] args) {SpringApplication.run(BookController.class, args);}}
右键run as --java application
效果
打开浏览器输入:
http://localhost:8080/bookInfo