詳解Spring中的@PropertySource注解使用
@PropertySource
注解是Spring用于加載配置文件,默認(rèn)支持.properties
與.xml
兩種配置文件。@PropertySource
屬性如下:
- name:默認(rèn)為空,不指定
Spring
自動(dòng)生成 - value:配置文件
- ignoreResourceNotFound:沒有找到配置文件是否忽略,默認(rèn)
false
,4.0版本加入 - encoding:配置文件編碼格式,默認(rèn)
UTF-8
4.3版本才加入 - factory:配置文件解析工廠,默認(rèn):
PropertySourceFactory.class
4.3版本才加入,如果是之前的版本就需要手動(dòng)注入配置文件解析Bean
接下來就使用@PropertySource
來加載.properties
與.xml
配置文件。這里模擬連接MySQL
數(shù)據(jù)庫。
首先添加依賴:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency>
準(zhǔn)備屬性配置文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306 jdbc.userName=root jdbc.password=xiaohu
創(chuàng)建屬性實(shí)體類來加載配置文件JdbcProperties
@Data @Repository @PropertySource(value = "classpath:jdbc.properties") public class JdbcProperties { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.userName}") private String userName; @Value("${jdbc.password}") private String password; }
創(chuàng)建JDBC配置類JdbcConfig
@Component public class JdbcConfig { @Bean public DataSource dataSource(JdbcProperties jdbcProperties){ System.out.println("打印獲取到的配置信息:"+jdbcProperties); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(jdbcProperties.getDriver()); dataSource.setUrl(jdbcProperties.getUrl()); dataSource.setUsername(jdbcProperties.getUserName()); dataSource.setPassword(jdbcProperties.getPassword()); return dataSource; } }
創(chuàng)建Spring
配置類SpringConfiguration
@Configuration public class SpringConfiguration { }
創(chuàng)建測試類測試讀取配置文件
public class PropertySourceTest { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("config"); DataSource dataSource = context.getBean("dataSource",DataSource.class); System.out.println(dataSource); } }
查看輸出結(jié)果:
打印獲取到的配置信息:JdbcProperties(driver=com.mysql.cj.jdbc.Driver, url=jdbc:mysql://127.0.0.1:3306, userName=root, password=xiaohu)
org.springframework.jdbc.datasource.DriverManagerDataSource@58695725
從結(jié)果可以看出,我們的properties
中的配置已經(jīng)成功讀取到,并且DataSource
也從Spring
容器中獲取到。上面介紹注解的屬性時(shí),factory
是4.3版本才加入的,那么如果4.3版本之前要解析配置文件又應(yīng)該怎么處理呢?,這個(gè)時(shí)候就需要手動(dòng)將解析配置文件的Bean注入到Spring
容器中了,用法很簡單,在SpringConfiguration
類中添加如下代碼即可:
@Bean public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); }
具體測試結(jié)果,就自行測試了。上面例子介紹了properties
的使用,下面我們將配置文件換成xml
文件。配置如下:
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <entry key="jdbc.driver">com.mysql.cj.jdbc.Driver</entry> <entry key="jdbc.url">jdbc:mysql://127.0.0.1:3306/test</entry> <entry key="jdbc.userName">root</entry> <entry key="jdbc.password">xiaohu</entry> </properties>
然后將JdbcProperties
類上的注解的配置文件換成xml
文件。
@PropertySource(value = "classpath:jdbc.properties")
其他不用調(diào)整,執(zhí)行測試類,輸出的結(jié)果一樣。因?yàn)樯厦娼榻B到@PropertySource
默認(rèn)支持properties
與xml
的配置文件。我們可以查看PropertySourceFactory
的默認(rèn)實(shí)現(xiàn)DefaultPropertySourceFactory
源碼
public class DefaultPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException { return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource)); } }
然后進(jìn)入ResourcePropertySource
類,源碼這里使用了一個(gè)三元運(yùn)算符,如果name
為空,就使用默認(rèn)Spring
默認(rèn)生成的name
。
public ResourcePropertySource(String name, EncodedResource resource) throws IOException { super(name, PropertiesLoaderUtils.loadProperties(resource)); this.resourceName = getNameForResource(resource.getResource()); } public ResourcePropertySource(EncodedResource resource) throws IOException { super(getNameForResource(resource.getResource()), PropertiesLoaderUtils.loadProperties(resource)); this.resourceName = null; }
這里可以看到調(diào)用了PropertiesLoaderUtils.loadProperties
方法,進(jìn)入到源碼
public static Properties loadProperties(EncodedResource resource) throws IOException { Properties props = new Properties(); fillProperties(props, resource); return props; }
會(huì)調(diào)用fillProperties
的方法,一直跟到調(diào)用最低的fillProperties
方法。
static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister) throws IOException { InputStream stream = null; Reader reader = null; try { String filename = resource.getResource().getFilename(); if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { stream = resource.getInputStream(); persister.loadFromXml(props, stream); } else if (resource.requiresReader()) { reader = resource.getReader(); persister.load(props, reader); } else { stream = resource.getInputStream(); persister.load(props, stream); } } finally { if (stream != null) { stream.close(); } if (reader != null) { reader.close(); } } }
第一個(gè)if
判斷文件后綴是否是xml
結(jié)尾,常量XML_FILE_EXTENSION
如下:
private static final String XML_FILE_EXTENSION = ".xml";
除了支持properties
與xml
的配置文件方式,也支持yml
配置文件的方式,不過需要自定義解析工廠,下面來實(shí)現(xiàn)怎么解析yml
配置文件。引入可以解析yml
文件的第三方庫
<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.28</version> </dependency>
創(chuàng)建yml
解析工廠YamlPropertySourceFactory
實(shí)現(xiàn)PropertySourceFactory
public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean(); factoryBean.setResources(resource.getResource()); Properties properties = factoryBean.getObject(); return name != null ? new PropertiesPropertySource(name, properties) : new PropertiesPropertySource(resource.getResource().getFilename(), properties); } }
然后將JdbcProperties
類的@PropertySource
換成如下寫法:
@PropertySource(value = "classpath:jdbc.yml",factory = YamlPropertySourceFactory.class)
執(zhí)行測試類,輸出結(jié)果與上面結(jié)果一樣
打印獲取到的配置信息:JdbcProperties(driver=com.mysql.cj.jdbc.Driver, url=jdbc:mysql://127.0.0.1:3306, userName=root, password=xiaohu)
org.springframework.jdbc.datasource.DriverManagerDataSource@58695725
證明我們自定義的解析yml
配置文件就成功了。
到此這篇關(guān)于Spring的@PropertySource注解使用的文章就介紹到這了,更多相關(guān)Spring的@PropertySource注解使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot使用Redis實(shí)現(xiàn)消息隊(duì)列的方法小結(jié)
在應(yīng)用中把Redis當(dāng)成消息隊(duì)列來使用已經(jīng)屢見不鮮了,我想主要原因是當(dāng)代應(yīng)用十有八九都會(huì)用到 Redis,因此不用再引入其他消息隊(duì)列系統(tǒng),而且Redis提供了好幾種實(shí)現(xiàn)消息隊(duì)列的方法,用起來也簡單,本文給大家介紹了SpringBoot使用Redis實(shí)現(xiàn)消息隊(duì)列的方法小結(jié)2024-04-04SpringBoot3.x集成nacos并實(shí)現(xiàn)多環(huán)境配置的操作步驟
本文詳細(xì)介紹了如何在Springboot3.x中集成Nacos2.x版本,包括nacos的安裝、配置更改,以及在集成過程中遇到的問題,如端口設(shè)置、依賴版本調(diào)整等,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10Java/Android 實(shí)現(xiàn)簡單的HTTP服務(wù)器
這篇文章主要介紹了Java/Android 如何實(shí)現(xiàn)簡單的HTTP服務(wù)器,幫助大家更好的進(jìn)行功能測試,感興趣的朋友可以了解下2020-10-10Java IO流和文件操作實(shí)現(xiàn)過程解析
這篇文章主要介紹了Java IO流和文件操作實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10Hibernate validator使用以及自定義校驗(yàn)器注解
這篇文章主要介紹了Hibernate validator使用以及自定義校驗(yàn)器注解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01springboot集成mybatisPlus+多數(shù)據(jù)源的實(shí)現(xiàn)示例
這篇文章主要介紹了springboot集成mybatisPlus+多數(shù)據(jù)源的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12JAVA學(xué)習(xí)筆記:注釋、變量的聲明和定義操作實(shí)例分析
這篇文章主要介紹了JAVA學(xué)習(xí)筆記:注釋、變量的聲明和定義操作,結(jié)合實(shí)例形式分析了Java注釋、變量的聲明和定義相關(guān)原理、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下2020-04-04