通过默认配置文件注入
springboot中默认的配置文件为application.yml或者application.properties文件,所以我们可以将属性配置在这两个文件中进行注入(以application.yml文件为例)
- 添加属性app.name到application.yml文件中
server:
port: 8888
app:
name: demo2
- 在代码中进行注入,将app.name注入到AppConfig.java对象中
将配置文件属性注入到bean对象种主要有两种方式,一种是@ConfigurationProperties方式注入,另一种是@Value方式注入.两种注入方式的具体区别,可参考我的另一篇博客SpringBoot @value注入与@ConfigurationProperties注入对比
此处我们使用@ConfigurationProperties方式注入,这个比较常见与食用
package com.mary.demo.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Created by marylgao on 2020/3/13.
*/
@Configuration
@ConfigurationProperties(prefix = "app")
public