版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaomingyang/article/details/84554323
通过@PropertySource注解将properties文件中的值存储到Environment中,Environment接口提供提供方法去读取配置文件中的值,参数是properties文件中配置的key值。
- 定义一个People类读取jdbc.properties配置文件中的值
package com.config.server.endpoint;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@PropertySource(value = {"classpath:jdbc.properties"})
@Component
@ConfigurationProperties(prefix = "com.yaomy.demo")
public class People {
private String username;
private String password;
private int age;
private int sex;
//省略setter和getter方法
}
- properties配置文件
com.yaomy.demo.username=玛丽66
com.yaomy.demo.password=12345666
com.yaomy.demo.age=1266
com.yaomy.demo.sex=166
- 测试主类
package com.config.server;
import com.config.server.endpoint.People;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.ApplicationContext;
@EnableConfigServer
@SpringBootApplication
public class ServerApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ServerApplication.class, args);
People obj = context.getBean("people", People.class);
System.out.println(obj.getUsername());
People obj1 = context.getBean("people", People.class);
System.out.println(obj1.getSex());
}
}
- 输出的结果是
玛丽66
166