1. 程式人生 > >Spring_屬性占位符

Spring_屬性占位符

基於 jdb version color spa xmlns play 根據 val

忍耐和堅持雖是痛苦的事情,但卻能漸漸地為你帶來好處。——奧維德

屬性占位符

  Spring一直支持將屬性定義到外部的屬性的文件中,並使用占位符值將其插入到Spring bean中。

  占位符的形式為使用"${}"包裝的屬性名稱,為了使用屬性占位符,我們必須配置一個PropertyPlaceholderConfigurer或PropertySourcesPlaceholderConfigurer實例,從Spring 3.0開始,推薦使用PropertySourcesPlaceholderConfigurer,因為它能夠基於Spring Environment及其屬性源來解析占位符。

  1.在基於Java配置中使用屬性占位符註入屬性

package chapter3.prctice6;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;

@Component
public class AppleMobile implements Mobile {
    
    
private String color; private String type; public AppleMobile(@Value("${mobile.color}") String color, @Value("${mobile.type}") String type) { this.color = color; this.type = type; } @Bean public PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer(); } public void play() { System.out.println(color+"-"+type); } }

  2.在基於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:aop="http://www.springframework.org/schema/aop"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc 
http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd"
> <bean id="appleMobile" class="chapter3.prctice6.AppleMobile" c:color="${moble.color}" c:type="${mobile.type}"> </bean> <context:property-placeholder/> </beans>

  解析外部屬性能夠將值的處理推遲到運行時,它的關註點在於根據名稱解析來自於Spring Environment和屬性源的屬性。

Spring_屬性占位符