javascript
springboot 前缀_SpringBoot配置文件的注入
需要了解更多java知識(shí)的朋友關(guān)注我的專(zhuān)欄,持續(xù)更新java知識(shí)。
Java架構(gòu)雜貨鋪?zhuanlan.zhihu.com1. 使用@PropertySource
使用 @PropertySource 注解可以從外部加載指定的配置文件,將配置文件與 JavaBean 相綁定,使 JavaBean 讀取配置文件中的值
在類(lèi)路徑下創(chuàng)建一個(gè) 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") // 對(duì)應(yīng)配置文件中的前綴 @PropertySource(value = {"classpath:people.properties"}) // 指定從類(lèi)路徑下的 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') 指定了配置文件中使用的前綴,對(duì)應(yīng)配置文件中的people.xxx 配置項(xiàng),而 @PropertySource(value = {"classpath:xxx}") 則指定了從類(lèi)路徑下獲取配置文件的信息
2. 使用@ImportResourse
使用@ImportResourse 注解可以導(dǎo)入 Spring 的配置文件,讓配置文件里面的配置生效
先準(zhǔn)備一個(gè) 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>如果沒(méi)有進(jìn)行其他配置,那么該 Spring 的配置文件也是不會(huì)生效的,如果想讓配置文件生效,需要在主程序類(lèi)上加上 @ImportResource(locations = ...) 注解
@ImportResource(locations = {"classpath:beans.xml"}) // 導(dǎo)入類(lèi)路徑下的 Spring 配置文件 @SpringBootApplication public class Springboot02ConfigApplication {public static void main(String[] args) {SpringApplication.run(Springboot02ConfigApplication.class, args);} }但是在實(shí)際開(kāi)發(fā)中不可能為每一個(gè)組件都單獨(dú)配置一個(gè) xxx.xml 文件,然后再使用注解的方式進(jìn)行導(dǎo)入,這樣過(guò)于麻煩
SpringBoot 中推薦使用配置類(lèi)的方法給容器中添加組件
新建一個(gè)配置類(lèi) MyApplicationConfig
@Configuration public class MyApplicationConfig {@Beanpublic HelloService helloService() {System.out.println("helloService組件");return new HelloService();} }其中的 @Configuration 注解用來(lái)指名當(dāng)前類(lèi)是一個(gè)配置類(lèi),替代 Spring 的 xml 配置文件,@Bean 注解類(lèi)似于之前 Spring 配置文件中的 <bean><bean/> 標(biāo)簽。
這里我將 HelloService 方法的返回值添加到 Spring 的容器中,該組件的默認(rèn) id 就是方法的名字,即 helloService
總結(jié)
以上是生活随笔為你收集整理的springboot 前缀_SpringBoot配置文件的注入的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 离开当前屏幕的判断方法_Android
- 下一篇: gradle idea java ssm