(测试发现${employee.username}所在类必须要注入(放在controller、service、compnent…下)并且@test 或者new 对象获取不到值)
package com.it.sm2.signsm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//springboot 读取配置第一种方式
@Component
@Data
public class Employee {
@Value("${employee.username}")
private String username;
@Value("${employee.password}")
private Long password;
@Value("${employee.age}")
private Integer age;
}
package com.it.sm2.signsm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
//springboot 读取配置第二种方式
@Component
@ConfigurationProperties(prefix = "department")
@Data
public class Department {
private String username;
private Long password;
private Integer age;
}
package com.it.sm2.signsm;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class FirstController {
@Value("${employee.username}")
private String username;
@Value("${employee.password}")
private Long password;
@Autowired
private Employee se;
@RequestMapping("/")
@ResponseBody
String home()
{
return "Hello Springboot!";
}
@RequestMapping("/hello")
@ResponseBody
String hello()
{
//测试new 是否可以获取@value;只能使用注入
// Employee e = new Employee();
String ss =se.getUsername();
return "username: " + username + ", " + "password: " + password+ss;
}
//test不能获取到值,@value 是获取的容器的配置值
@Test
public void s(){
System.out.println(this.password);
}
}
department.username= ddd
department.password: 222
department.age: 22
employee.username=sss
employee.password=111
employee.age=11