欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2021年06月15日 10:06:01   作者:pan_junbiao  
這篇文章主要介紹了Spring使用@Value注解與@PropertySource注解加載配置文件操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

1、@Value注解簡介

Spring框架提供的@Value注解可以將外部的值動態(tài)注入到Bean中,@Value注解使用在字段、構(gòu)造器參數(shù)和方法參數(shù)上。

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

此注解值的注入發(fā)生在AutowiredAnnotationBeanPostProcessor類中。

@Value注解實現(xiàn)以下幾種情況:

(1)注入普通字符;

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

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

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

(5)注入文件內(nèi)容;

(6)注入網(wǎng)址內(nèi)容;

(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)創(chuàng)建用戶信息屬性文件(user.properties)

user.userId=1
user.userName=pan_junbiao的博客
user.blogUrl=https://blog.csdn.net/pan_junbiao
user.remark=您好,歡迎訪問 pan_junbiao的博客

(2)創(chuàng)建用戶信息實體類(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());
}

執(zhí)行結(jié)果:

3、綜合實例

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

(1)添加相關(guān)的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 可以簡化文件相關(guān)操作,本實例中使用 commons-io 將 file 轉(zhuǎn)換成字符串。

(2)創(chuàng)建資源文件

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

在resources資源目錄下創(chuàng)建數(shù)據(jù)庫連接配置文件db.properties,該文件配置如下:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_admin
jdbc.username=root
jdbc.password=123456

(3)需被注入的Bean

創(chuàng)建名為OtherUser.java的用戶信息類。

package com.pjb.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
/**
 * 用戶信息類
 * @author pan_junbiao
 **/
@Component
public 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)配置類

創(chuàng)建名為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;
 
    /**
     * 注入操作系統(tǒng)屬性
     */
    @Value("#{systemProperties['os.name']}")
    private String osName;
 
    /**
     * 注入表達式運算結(jié)果
     */
    @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;
 
    /**
     * 注入網(wǎng)址資源
     */
    @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("注入操作系統(tǒng)屬性:");
            System.out.println(osName);
            System.out.println("------------------------------------------------");
 
            System.out.println("注入表達式運算結(jié)果:");
            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("文件中的內(nèi)容:" + IOUtils.toString(testFile.getInputStream()));
            System.out.println("------------------------------------------------");
 
            System.out.println("注入配置文件(方式一):");
            System.out.println("數(shù)據(jù)庫驅(qū)動:" + jdbc_driver);
            System.out.println("數(shù)據(jù)庫連接:" + jdbc_url);
            System.out.println("數(shù)據(jù)庫用戶:" + jdbc_username);
            System.out.println("數(shù)據(jù)庫密碼:" + jdbc_password);
            System.out.println("------------------------------------------------");
 
            System.out.println("注入配置文件(方式二):");
            System.out.println("數(shù)據(jù)庫驅(qū)動:" + environment.getProperty("jdbc.driver"));
            System.out.println("數(shù)據(jù)庫連接:" + environment.getProperty("jdbc.url"));
            System.out.println("數(shù)據(jù)庫用戶:" + environment.getProperty("jdbc.username"));
            System.out.println("數(shù)據(jù)庫密碼:" + 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();
    }
}

執(zhí)行結(jié)果:

spring中@value注解需要注意

首先

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

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

或者

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

其次

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

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

classpath:/config/t1.properties

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

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

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

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

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

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="location">
    <value>config/t1.properties</value>
    </property>
</bean>**重點內(nèi)容**

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java設(shè)計模式之裝飾者模式詳解

    Java設(shè)計模式之裝飾者模式詳解

    這篇文章主要為大家詳細介紹了java設(shè)計模式之裝飾者模式,裝飾者模式是一種結(jié)構(gòu)式模式,感興趣的朋友可以參考一下
    2021-10-10
  • Java異常的處理機制

    Java異常的處理機制

    這篇文章主要介紹了Java異常的處理機制,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • Java中final變量使用總結(jié)

    Java中final變量使用總結(jié)

    這篇文章主要介紹了Java中final變量使用總結(jié),final關(guān)鍵字可用于變量聲明,一旦該變量被設(shè)定,就不可以再改變該變量的值,通常final定義的變量為常量,需要的朋友可以參考下
    2015-06-06
  • 使用Easyexcel實現(xiàn)不同場景的數(shù)據(jù)導(dǎo)出功能

    使用Easyexcel實現(xiàn)不同場景的數(shù)據(jù)導(dǎo)出功能

    這篇文章主要為大家詳細介紹了如何在不同場景下使用Easyexcel實現(xiàn)數(shù)據(jù)導(dǎo)出功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • Java實現(xiàn)不同的類的屬性之間相互賦值

    Java實現(xiàn)不同的類的屬性之間相互賦值

    今天小編就為大家分享一篇關(guān)于Java實現(xiàn)不同的類的屬性之間相互賦值,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • 使用IntelliJ IDEA 進行代碼對比的方法(兩種方法)

    使用IntelliJ IDEA 進行代碼對比的方法(兩種方法)

    這篇文章給大家?guī)砹藘煞NIntelliJ IDEA 進行代碼對比的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2018-01-01
  • Java多線程中ReentrantLock與Condition詳解

    Java多線程中ReentrantLock與Condition詳解

    這篇文章主要介紹了Java多線程中ReentrantLock與Condition詳解,需要的朋友可以參考下
    2017-11-11
  • Spring Boot設(shè)置并使用緩存的步驟

    Spring Boot設(shè)置并使用緩存的步驟

    今天小編就為大家分享一篇關(guān)于Spring Boot設(shè)置并使用緩存的步驟,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • 淺談JSP是如何編譯成servlet并提供服務(wù)的

    淺談JSP是如何編譯成servlet并提供服務(wù)的

    JSP是Servlet的一種特殊形式,JSP頁面最終是編譯為Servlet執(zhí)行的,那么本文主要介紹了JSP是如何編譯成servlet并提供服務(wù)的,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • MyBatis自定義SQL攔截器示例詳解

    MyBatis自定義SQL攔截器示例詳解

    Mybatis支持對Executor、StatementHandler、PameterHandler和ResultSetHandler 接口進行攔截,也就是說會對這4種對象進行代理,下面這篇文章主要給大家介紹了關(guān)于MyBatis自定義SQL攔截器的相關(guān)資料,需要的朋友可以參考下
    2021-10-10

最新評論