码迷,mamicode.com
首页 > 编程语言 > 详细

Spring_属性占位符

时间:2018-04-17 00:03:00      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:out   基于   注入   文件中   使用   XML   www   包装   context   

忍耐和坚持虽是痛苦的事情,但却能渐渐地为你带来好处。——奥维德

属性占位符

  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_属性占位符

标签:out   基于   注入   文件中   使用   XML   www   包装   context   

原文地址:https://www.cnblogs.com/dandelZH/p/8859090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!