一、这样读取
package com.forezp.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by fangzhipeng on 2017/4/18.
*/
@RestController
public class MiyaController {
@Value("${my.name}")
private String name;
@Value("${my.age}")
private int age;
@RequestMapping(value = "/miya")
public String miya(){
return name+":"+age;
}
}
二、application.yml
my:
name: dg
age: 124
number: ${random.int}
uuid : ${random.uuid}
max: ${random.int(10)}
value: ${random.value}
greeting: welcome,取值来这里。
spring:
profiles:
active: dev
--------------------------
方式二: 到javabean中去读取
1、配置文件
package com.forezp.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created by fangzhipeng on 2017/4/18.
*/
@ConfigurationProperties(prefix = "my") /*这里对应配置文件里面的标签my,可以读取那里面的内容*/
@Component
public class ConfigBean {
private String name;
private int age;
private int number;
private String uuid;
private int max;
private String value;
private String greeting;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
2、
package com.forezp.web;
import com.forezp.bean.ConfigBean;
import com.forezp.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by fangzhipeng on 2017/4/18.
*/
@RestController
@EnableConfigurationProperties({ConfigBean.class,User.class})
public class LucyController {
@Autowired
ConfigBean configBean;
@RequestMapping(value = "/lucy")
public String miya(){
return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getAge()+" >>>>"+configBean.getMax();
}
/* 访问控制加了这个 @EnableConfigurationProperties({ConfigBean.class,User.class})*/
@Autowired
User user;
@RequestMapping(value = "/user")
public String user(){
return user.getName()+user.getAge();
}
}