javascript
springboot 前缀_SpringBoot配置文件的注入
需要了解更多java知識的朋友關注我的專欄,持續更新java知識。
Java架構雜貨鋪?zhuanlan.zhihu.com1. 使用@PropertySource
使用 @PropertySource 注解可以從外部加載指定的配置文件,將配置文件與 JavaBean 相綁定,使 JavaBean 讀取配置文件中的值
在類路徑下創建一個 people.properties 文件
people.last-name=張三三 people.age=100 people.birth=2019/2/3 people.boss=false people.maps.password=lwh123 people.maps.address=xxx people.lists=a,b,c,d,e people.dog.name=dog people.dog.age=19在 Bean 在綁定該配置文件
@Component @ConfigurationProperties(prefix = "people") // 對應配置文件中的前綴 @PropertySource(value = {"classpath:people.properties"}) // 指定從類路徑下的 people.properties 文件獲取配置文件的值 public class People {private String lastName;private Integer age;private Boolean boss;private Date birth;private Map<String, String> maps;private List<String> lists;private Dog dog;// 省略 getter/setter 方法// 省略 toString 方法 }這里的 @ConfigurationProperties(prefix = 'people') 指定了配置文件中使用的前綴,對應配置文件中的people.xxx 配置項,而 @PropertySource(value = {"classpath:xxx}") 則指定了從類路徑下獲取配置文件的信息
2. 使用@ImportResourse
使用@ImportResourse 注解可以導入 Spring 的配置文件,讓配置文件里面的配置生效
先準備一個 Spring 的配置文件 beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="Index of /schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="Index of /schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="helloService" class="edu.just.springboot.service.HelloService"></bean></beans>如果沒有進行其他配置,那么該 Spring 的配置文件也是不會生效的,如果想讓配置文件生效,需要在主程序類上加上 @ImportResource(locations = ...) 注解
@ImportResource(locations = {"classpath:beans.xml"}) // 導入類路徑下的 Spring 配置文件 @SpringBootApplication public class Springboot02ConfigApplication {public static void main(String[] args) {SpringApplication.run(Springboot02ConfigApplication.class, args);} }但是在實際開發中不可能為每一個組件都單獨配置一個 xxx.xml 文件,然后再使用注解的方式進行導入,這樣過于麻煩
SpringBoot 中推薦使用配置類的方法給容器中添加組件
新建一個配置類 MyApplicationConfig
@Configuration public class MyApplicationConfig {@Beanpublic HelloService helloService() {System.out.println("helloService組件");return new HelloService();} }其中的 @Configuration 注解用來指名當前類是一個配置類,替代 Spring 的 xml 配置文件,@Bean 注解類似于之前 Spring 配置文件中的 <bean><bean/> 標簽。
這里我將 HelloService 方法的返回值添加到 Spring 的容器中,該組件的默認 id 就是方法的名字,即 helloService
總結
以上是生活随笔為你收集整理的springboot 前缀_SpringBoot配置文件的注入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 离开当前屏幕的判断方法_Android
- 下一篇: python安装vpython_VPyt