多环境选择
- 含义
- 相同代码在不同环境的运行
- 不同环境下执行不同的实现类
- 步骤:
- 多配置文件的方式
- 设置多个配置文件,格式application-dev.yml
- 主配置文件选择不同环境的配置文件
- 在接口上添加@Profile进行环境选择
- 访问结果
- 同时在打包完后可以使用–spring.profiles.active=prod,来动态的配置环境,而不用重新打包
- 单配置文件的方式
- 直接在一个配置文件中进行配置
- 多配置文件的方式
读取自定义配置
- 步骤
- 通过@Value("${}")读取application.yml中的指定的属性值
- 通过在类上添加@PropertySource(value=“路径”)来读取自定义的配置文件
- 此处文件的格式必须是properties文件,不能使用yml文件
- 如果application.yml和配置的路径中都存在相同的属性,则优先使用application.yml中的值。路径中的值不会被使用。如果出现乱码,在PropertySource中使用encoding=“utf-8”
- 读取对象属性:
- 使用PropertySource读取时,可以进行整体读,将配置文件中的内容读取到一个实体类中
- 步骤
- 创建配置文件 student.properties
student.name=Tom student.age=10 student.sex=女 people.name=Cat
- 创建实体类对象
@Component //创建get set方法,去除该字段后,student的属性值为默认值,即没有注入,底层应该是通过get set反射进行注入。 @Data //读取配置文件 @PropertySource(value="classpath:student.properties",encoding="utf-8") //获取配置文件中以student开头key的信息 @ConfigurationProperties("student") public class Student { private String name; private int age; private String sex; @Override public String toString() { return "student[name="+name+",age="+age+",sex="+sex+"]"; } } ```
- 测试
@PropertySource(value = "classpath:student.properties") @RestController public class StudentController { @Value("${people.name}") private String name; //自动注入刚才获取到的student @Autowired private Student student; @RequestMapping("/people") public String hello(){ return "Hello world " + name; } @RequestMapping("/student") public String person(){ return student.toString(); } }
- 显示结果