读取yml配置信息
@Value("${province}") private String province; @Value("${user.sname}") private String name1; @Value("${user1[1].name}") private String name; @Value("${server.port}") private int port;
server: port: 8099 #counter: china province: beijing # # user: sname: 一一丫丫 age: 18 sex: 1 # #spring: # mvc: # servlet: # load-on-startup: 1 user1: - name: 10086 age: 10989 sex: 99 - name: 香香 age: 83 sex: 33
province===================>beijing
age===================>limin
name===================>香香
port===================>8099
上面的方式太繁琐,使用 @Autowire自动封装
//使用自动装配将所有的数据封装到一个对象中 @Autowired private Environment env;
System.out.println("tempdir==============>"+env.getProperty("user1[0].name"));
tempdir==============>10086
上下文属性
修改
读取yml中某一块数据
封装对象
//1 定义数据模型,封装yml文件中对应的数据 import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; //2 定义 Spring管控的bean @Component //3.指定加载的数据 @ConfigurationProperties(prefix = "datasource") public class MyDataSource { private String driver; private String url; private String username; private String password; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "MyDataSource{" + "driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
@Autowired private MyDataSource myDataSource;
System.out.println(myDataSource.getDriver()); System.out.println(myDataSource.getUrl()); System.out.println(myDataSource.getUsername()); System.out.println(myDataSource.getPassword()); System.out.println(myDataSource);
com.postgresql.jdbc.Driver
urllllllllll
null
root666
MyDataSource{driver='com.postgresql.jdbc.Driver', url='urllllllllll', username='null', password='**'}