@Value:属性注入
@ConfigurationProperties(prefix = "user") 绑定
示例
controller
package com.ludb.springbootc.controller;
import com.ludb.springbootc.vo.User;
import com.ludb.springbootc.vo.User2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Hello {
@Autowired
private User a ;
@Autowired
private User2 a2 ;
@RequestMapping("/hello")
public String hello (){
return a.getUserName()+"-------"+a2.getUserName()
+"------------"+a2.getAdd()+"------------"+a2.getSex()+"------------"+a2.getRan();
}
}
User
package com.ludb.springbootc.vo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//把普通pojo实例化到spring容器中,相当于配置文件中的 <bean id="" class=""/>
@Component
public class User {
//可以通过@value+SPEL 直接绑定参数
@Value("${user.userName}")
private String userName;
@Value("${user.age}")
private String age;
public void setUserName(String userName) {
this.userName = userName;
}
public void setAge(String age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public String getAge() {
return age;
}
}
User2
package com.ludb.springbootc.vo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.xml.crypto.Data;
//把普通pojo实例化到spring容器中,相当于配置文件中的 <bean id="" class=""/>
@Component
//指定配置文件中的某个节点,该节点中的子节点将自动和属性绑定
@ConfigurationProperties(prefix = "user")
public class User2 {
private String userName;
private String age;
private String add;
private String sex;
private String ran;
public String getRan() {
return ran;
}
public void setRan(String ran) {
this.ran = ran;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public String getUserName() {
return userName;
}
public void setAge(String age) {
this.age = age;
}
}
SpringbootCApplication
package com.ludb.springbootc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootCApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootCApplication.class, args);
}
}
application.yaml
#application.yaml文件
server:
port: 8080
servlet:
context-path: /hellos
spring:
profiles:
active: uat
application-uat.yaml
#application-uat.yaml文件
server:
port: 8081
user:
userName: asd
age: 士大夫
#引用其他配置的值
add: ${user.age}
#随机数(1到99)
sex: ${random.int[1,100]}
#随机id
ran: ${random.uuid}
测试