一、新建properties文件
在resources目录下,新建一个 fy.properties 文件。
test.fy.name=best
test.fy.pwd=pwd123@
二、定义配置类
@Configuration
@PropertySource("classpath:fy.properties")
注意这里的配置路径
package com.springboot.springboot_web.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:fy.properties")
public class FySettings {
@Value("${test.fy.name}")
private String name;
@Value("${test.fy.pwd}")
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
三、应用
注入一下
@Resource
FySettings fySettings;
package com.springboot.springboot_web.control;
import com.springboot.springboot_web.config.FySettings;
import com.springboot.springboot_web.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.Date;
@Controller
@RequestMapping("/fastjson")
public class FastjsonController {
@Resource
FySettings fySettings;
@RequestMapping("/test")
@ResponseBody
public User testJson() {
User user = new User();
user.setId(1);
user.setUsername(fySettings.getName());
user.setPassword(fySettings.getPwd());
user.setBirthday(new Date());
return user;
}
}
测试一下,访问路径 http://127.0.0.1:8081/fastjson/test
{
"birthday": "2018-08-20 05:05:09",
"id": 1,
"password": "pwd123@",
"username": "best"
}