文章出處

前言

譯文鏈接:http://websystique.com/spring/spring-propertysource-value-annotations-example/

本篇文章將展示如何通過@PropertySource@Value注解從配置文件中讀取屬性值。

同樣,我們也會討論Spring的Environment接口,還會看到使用XML配置和使用注解的對比。

Spring的@PropertySource注解主要是讓Spring的Environment接口讀取屬性配置文件用的,這個注解是標識在@Configuration配置類上的。

Spring的@Value注解可以用在字段和方法上。通常用于從屬性配置文件中讀取屬性值,也可以設置默認值。接下來就讓我么看下完整的例子吧。

涉及的技術及開發工具

  • Spring 4.0.6.RELEASE
  • Maven 3
  • JDK 1.6
  • Eclipse JUNO Service Release 2

工程結構目錄

步驟一:往pom.xml中添加依賴

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.websystique.spring</groupId>
    <artifactId>Spring4PropertySourceExample</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
 
    <name>Spring4PropertySourceExample</name>
 
    <properties>
        <springframework.version>4.0.6.RELEASE</springframework.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
 
</project>

步驟二:創建Spring配置類

Spring配置類是指用@Configuration注解標注的類,這些類包含了用@Bean標注的方法。這些被@Bean標注的方法可以生產bean并交由spring容器管理。

package com.websystique.spring.configuration;
 
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;
 
@Configuration
@ComponentScan(basePackages = "com.websystique.spring")
@PropertySource(value = { "classpath:application.properties" })
public class AppConfig {
 
    /*
     * PropertySourcesPlaceHolderConfigurer Bean only required for @Value("{}") annotations.
     * Remove this bean if you are not using @Value annotations for injecting properties.
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

@PropertySource(value = { “classpath:application.properties” })注解可以讓在application.properties文件中定義的屬性對Spring Envirronment bean可用,Environment接口提供了getter方法讀取單獨的屬性值。

注意PropertySourcesPlaceholderConfigurer這個bean,這個bean主要用于解決@value中使用的${…}占位符。假如你不使用${…}占位符的話,可以不使用這個bean。

以上的配置使用XML替代的話,如下:

app-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
    <context:component-scan base-package="com.websystique.spring"/>
 
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
          <list>
            <value>classpath:application.properties</value>
          </list>
        </property>
      </bean>
</beans>

步驟三:創建配置文件

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/websystique
jdbc.username = myuser
jdbc.password = mypassword
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false
sourceLocation = /dev/input

我們將會在service類里使用上面提到的配置方式讀取這個配置文件

步驟四:創建服務類

package com.websystique.spring.service;
 
public interface FileService {
 
    void readValues();
}
package com.websystique.spring.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
 
@Service("fileService")
public class FileServiceImpl implements FileService {
 
    @Value("${sourceLocation:c:/temp/input}")
    private String source;
 
    @Value("${destinationLocation:c:/temp/output}")
    private String destination;
 
    @Autowired
    private Environment environment;
 
    public void readValues() {
        System.out.println("Getting property via Spring Environment :"
                + environment.getProperty("jdbc.driverClassName"));
 
        System.out.println("Source Location : " + source);
        System.out.println("Destination Location : " + destination);
         
    }
 
}

這里首先要注意的是Environment bean被Spring自動注入。另外,由于配置了@PropertySoruce注解,Environment bean可以訪問指定配置文件里定義的所有屬性值。你可以使用getProperty方法得到指定值。

另外一點值得注意的是@Value注解,基本格式如下:

@value("${key:default")
private String var;

以上聲明指導spring根據key去屬性配置文件查找value,如果沒找到,則使用default作為默認值。

注意以上的${…}占位符只有當注冊了PropertySourcesPlaceholderConfigurer bean后才能被解析,否則@Value注解會一直將默認值賦值給var。

步驟五:創建Main方法運行程序

package com.websystique.spring;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
 
import com.websystique.spring.configuration.AppConfig;
import com.websystique.spring.service.FileService;
 
public class AppMain {
     
    public static void main(String args[]){
        AbstractApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
        FileService service = (FileService) context.getBean("fileService");
         
        service.readValues();
        context.close();
    }
     
}

運行以上程序,得到如下結果:

Getting property via Spring Environment :com.mysql.jdbc.Driver
Source Location : /dev/input
Destination Location : c:/temp/output
由于destinationLocation屬性在application.properties文件中沒定義,所以使用默認值。
最后,若使用XML配置,請將
AbstractApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
替換為
AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");
即可,
會得到相同的輸出結果。

工程源碼

http://websystique.com/?smd_process_download=1&download_id=796


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()