本文主要是介绍java springboot通过EnableConfigurationProperties全局声明bean并处理装配,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Spring Boot中 我们想条件装配一个类 首先 我们要声明他的bean
而 EnableConfigurationProperties 可以直接将 要全局声明的类绑定在 属性类中
例如 我们随便创建一个类 就叫 textData 吧 参考代码如下
package com.example.webdom.domain;import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties("textdata")
public class textData {private int time;private String units;public int getTime() {return time;}public String getUnits() {return units;}public void setTime(int time) {this.time = time;}public void setUnits(String units) {this.units = units;}@Overridepublic String toString() {return "textData{" +"time=" + time +", units='" + units + '\'' +'}';}
}
这里 我们用 toString 限制了 后面输出整个类 输出两个属性 让人看得懂
然后 我们定义的两个属性 写上get和set方法 方便与外界交互
然后 注解 ConfigurationProperties 指定读取配置文件中的 textdata对象默认装配到我们这个类的属性中
既然都写了 ConfigurationProperties 用配置文件 textdata 了
我们找到 application 配置文件 加上这两个值 是什么值并不是很重要 反正类型和名字跟属性类对得上就行
然后 我们启动类编写代码如下
package com.example.webdom;import com.example.webdom.domain.textData;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;@SpringBootApplication
@EnableConfigurationProperties({textData.class})
public class WebDomApplication {public static void main(String[] args) {SpringApplication.run(WebDomApplication.class, args);}}
唯一特别的就是 @EnableConfigurationProperties({textData.class}) 我们指定 textData类 默认声明这个bean
不难看出 EnableConfigurationProperties中是个数组 可以给多个类的
然后 我们在需要用 textData类的地方 默认装配 然后输出
这里 我们textData中并没有声明bean的代码 但是 EnableConfigurationProperties声明了
所以我们就可以在项目的任何一个地方 直接去条件装配这个bean
运行结果如下
这个输出显然很完美 不但 textData拿到了 ConfigurationProperties也从配置文件中装配了属性
这篇关于java springboot通过EnableConfigurationProperties全局声明bean并处理装配的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!