场景

在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

SpringBoot中通过@Value获取自定义配置的值SpringBoot中通过@Value获取自定义配置的值

 

效果

打开浏览器输入:

http://localhost:8080/bookInfo

SpringBoot中通过@Value获取自定义配置的值SpringBoot中通过@Value获取自定义配置的值

相关文章:

  • 2021-11-23
  • 2022-12-23
  • 2022-02-09
  • 2021-08-28
  • 2021-11-23
  • 2021-11-23
  • 2022-12-23
猜你喜欢
  • 2022-03-04
  • 2021-06-17
  • 2022-12-23
  • 2021-09-07
  • 2021-05-24
  • 2022-12-23
相关资源
相似解决方案