一. 点睛
在之前的文章Spring4.x常用配置(二):Spring EL和资源调用中讲述了在常规Spring
环境下,注入properties
文件里面的值的方式,通过@PropertySource
指明properties
文件的位置,然后通过@Value
注入值。在Spring
Boot
里,我们只需在application.properties
定义属性,直接使用@Value
注入值即可。
二. 示例
1. application.properties增加属性:
article.author=longjiazuo
article.name=spring boot
2. 修改控制器类
控制器类如下所示:
package org.light4j.springboot.properties.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${article.author}")
private String articleAuthor;
@Value("${article.name}")
private String articleName;
@RequestMapping("/")
public String hello() {
return "article name is:" + articleName + " and article author is:" + articleName;
}
}
3. 运行
启动入口类Application
,访问http://localhost:8080/,效果如下图所示:
三. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » Spring Boot核心(六):常规属性配置