亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Spring使用@Value注解與@PropertySource注解加載配置文件操作

瀏覽:89日期:2023-07-10 11:32:00
1、@Value注解簡介

Spring框架提供的@Value注解可以將外部的值動態注入到Bean中,@Value注解使用在字段、構造器參數和方法參數上。

@Value可以指定屬性取值的表達式,支持通過#{}使用SpringEL來取值,也支持使用${}來將屬性來源中(Properties文件、本地環境變量、系統屬性等)的值注入到Bean的屬性中。

此注解值的注入發生在AutowiredAnnotationBeanPostProcessor類中。

@Value注解實現以下幾種情況:

(1)注入普通字符;

(2)注入操作系統屬性;

(3)注入表達式運算結果;

(4)注入其他Bean的屬性;

(5)注入文件內容;

(6)注入網址內容;

(7)注入屬性文件。

2、@PropertySource注解簡介

@PropertySource注解可以加載指定的屬性文件(*.properties)到 Spring 的 Environment 中??梢耘浜?@Value 和 @ConfigurationProperties 使用。語法格式如下:

@PropertySource(value = 'classpath:com/pjb/el/user.properties',encoding = 'UTF-8')public class UserInfo{}

【實例】使用@Value注解與@PropertySource注解加載配置文件。

(1)創建用戶信息屬性文件(user.properties)

user.userId=1user.userName=pan_junbiao的博客user.blogUrl=https://blog.csdn.net/pan_junbiaouser.remark=您好,歡迎訪問 pan_junbiao的博客(2)創建用戶信息實體類(UserInfo.java)

使用@PropertySource注解加載配置文件信息,然后使用@Value注解注入屬性值。

package com.pjb.el;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component; /** * 用戶信息實體類 * @author pan_junbiao **/@Component@PropertySource(value = 'classpath:com/pjb/el/user.properties',encoding = 'UTF-8')public class UserInfo{ //用戶ID @Value('${user.userId}') private int userId; //用戶姓名 @Value('${user.userName}') private String userName; //博客地址 @Value('${user.blogUrl}') private String blogUrl; //備注 @Value('${user.remark}') private String remark; //省略getter與setter方法...}(3)運行

public static void main(String[] args){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class); UserInfo userInfo = context.getBean(UserInfo.class); //打印用戶信息 System.out.println('用戶編號:' + userInfo.getUserId()); System.out.println('用戶姓名:' + userInfo.getUserName()); System.out.println('博客地址:' + userInfo.getBlogUrl()); System.out.println('備注信息:' + userInfo.getRemark());}

執行結果:

Spring使用@Value注解與@PropertySource注解加載配置文件操作

3、綜合實例

【實例】使用@Value注解實現多種情況值的注入和@PropertySource注解加載配置文件。

(1)添加相關的jar包

添加Spring支持及commons-io依賴,pom.xml文件的配置如下:

<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>5.2.3.RELEASE</spring.version></properties> <dependencies> <!-- Spring框架 --> <dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version> </dependency> <dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version> </dependency> <!-- commons-io依賴 --> <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version> </dependency></dependencies>

添加 commons-io.jar 可以簡化文件相關操作,本實例中使用 commons-io 將 file 轉換成字符串。

(2)創建資源文件

在resources資源目錄下創建名稱為info.txt的文本文件,文件內容為:您好,歡迎訪問 pan_junbiao的博客。

在resources資源目錄下創建數據庫連接配置文件db.properties,該文件配置如下:

jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/db_adminjdbc.username=rootjdbc.password=123456(3)需被注入的Bean

創建名為OtherUser.java的用戶信息類。

package com.pjb.el;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component; /** * 用戶信息類 * @author pan_junbiao **/@Componentpublic class OtherUser{ //用戶名稱 @Value('pan_junbiao的博客') private String userName; //博客地址 @Value('https://blog.csdn.net/pan_junbiao') private String blogUrl; public String getUserName() {return userName; } public void setUserName(String userName) {this.userName = userName; } public String getBlogUrl() {return blogUrl; } public void setBlogUrl(String blogUrl) {this.blogUrl = blogUrl; }}(4)配置類

創建名為ElConfig.java的配置類。

package com.pjb.el;import org.apache.commons.io.IOUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;import org.springframework.core.env.Environment;import org.springframework.core.io.Resource; /** * 配置類 * @author pan_junbiao **/@Configuration@ComponentScan('com.pjb.el')@PropertySource('classpath:db.properties')public class ElConfig{ /** * 注入普通字符串 */ @Value('您好,歡迎訪問 pan_junbiao的博客') private String comment; /** * 注入操作系統屬性 */ @Value('#{systemProperties[’os.name’]}') private String osName; /** * 注入表達式運算結果 */ @Value('#{ T(java.lang.Math).random() * 100.0 }') private double randomNumber; /** * 注入其他Bean的屬性 */ @Value('#{otherUser.userName}') private String fromUserName; @Value('#{otherUser.blogUrl}') private String fromBlogUrl; /** * 注入文件資源 */ @Value('classpath:info.txt') private Resource testFile; /** * 注入網址資源 */ @Value('https://blog.csdn.net/pan_junbiao') private Resource testUrl; /** * 注入配置文件 */ @Value('${jdbc.driver}') private String jdbc_driver; @Value('${jdbc.url}') private String jdbc_url; @Value('${jdbc.username}') private String jdbc_username; @Value('${jdbc.password}') private String jdbc_password; @Autowired private Environment environment; @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {return new PropertySourcesPlaceholderConfigurer(); } public void outputResource() {try{ System.out.println('注入普通字符串:'); System.out.println(comment); System.out.println('------------------------------------------------'); System.out.println('注入操作系統屬性:'); System.out.println(osName); System.out.println('------------------------------------------------'); System.out.println('注入表達式運算結果:'); System.out.println(randomNumber); System.out.println('------------------------------------------------'); System.out.println('注入其他Bean的屬性:'); System.out.println('用戶名稱:' + fromUserName); System.out.println('博客地址:'+ fromBlogUrl); System.out.println('------------------------------------------------'); System.out.println('注入文件資源:'); System.out.println('文件中的內容:' + IOUtils.toString(testFile.getInputStream())); System.out.println('------------------------------------------------'); System.out.println('注入配置文件(方式一):'); System.out.println('數據庫驅動:' + jdbc_driver); System.out.println('數據庫連接:' + jdbc_url); System.out.println('數據庫用戶:' + jdbc_username); System.out.println('數據庫密碼:' + jdbc_password); System.out.println('------------------------------------------------'); System.out.println('注入配置文件(方式二):'); System.out.println('數據庫驅動:' + environment.getProperty('jdbc.driver')); System.out.println('數據庫連接:' + environment.getProperty('jdbc.url')); System.out.println('數據庫用戶:' + environment.getProperty('jdbc.username')); System.out.println('數據庫密碼:' + environment.getProperty('jdbc.password')); System.out.println('------------------------------------------------');}catch (Exception ex){ ex.printStackTrace();} }}

注入配置配件需要使用@PropertySource注解指定文件地址,若使用@Value注解,則要配置一個PropertySourcesPlaceholderConfigurer的Bean。注意,@Value('${jdbc.driver}')使用的是“${}”而不是“#{}”。

注入Properties還可以從Environment中獲得。

(5)運行

package com.pjb.el;import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * 運行類 * @author pan_junbiao **/public class Main{ public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);ElConfig resourceService = context.getBean(ElConfig.class);resourceService.outputResource();context.close(); }}

執行結果:

Spring使用@Value注解與@PropertySource注解加載配置文件操作

spring中@value注解需要注意首先

@value需要參數,這里參數可以是兩種形式:

@Value(“#{configProperties[‘t1.msgname’]}”)

或者

@Value(“${t1.msgname}”);其次

下面我們來看看如何使用這兩形式,在配置上有什么區別:

1、@Value(“#{configProperties[‘t1.msgname’]}”)這種形式的配置中有“configProperties”,其實它指定的是配置文件的加載對象:配置如下:

classpath:/config/t1.properties

這樣配置就可完成對屬性的具體注入了;

2、@Value('${t1.msgname}')這種形式不需要指定具體加載對象,這時候需要一個關鍵的對象來完成PreferencesPlaceholderConfigurer,這個對象的配置可以利用上面配置1中的配置,也可以自己直接自定配置文件路徑。

如果使用配置1中的配置,可以寫成如下情況:

<bean class='org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer'> <property name='properties' ref='configProperties'/></bean>

如果直接指定配置文件的話,可以寫成如下情況:

<bean class='org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer'> <property name='location'> <value>config/t1.properties</value> </property></bean>**重點內容**

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 在浴室边摸边吃奶边做视频 | 国产精品免费麻豆入口 | 91tm视频| 免费网站你懂的 | 国产制服一区 | 伊人久热这里只有精品视频99 | 天天综合色 | 国产激情视频在线播放 | 在线91| 黄色一级大片视频 | 免费的全黄一级录像带 | 欧美一级毛片一级 | 国产美女久久久久久久久久久 | 午夜性视频播放免费视频 | 久久不卡日韩美女 | 青草国产精品久久久久久 | 免费精品视频 | 快色网站| 成人午夜影院在线观看 | 欧美日本一区亚洲欧美一区 | 亚洲色啦啦狠狠网站 | 久久网欧美 | 成年人黄色大片大全 | 男女无遮挡边做边吃视频免费 | 国产日韩欧美一区二区三区在线 | 婷婷色综合| 亚洲欧美日韩精品在线 | 欧美草逼片 | 亚洲欧美日韩综合二区三区 | 久久久久久综合对白国产 | 亚洲精品乱码久久久久久蜜桃欧美 | 成人深夜福利在线播放不卡 | 亚洲精品视频二区 | 伊人黄网 | 久久午夜青青草原影院 | 看片日韩 | 亚洲欧美一区二区三区在线 | 在线91色 | 欧美亚洲国产精品久久久久 | 亚洲精品视频在线看 | 麻豆国产入口在线观看免费 |