Spring Bean定義中表達式語言的支持

    SpEL(Spring Expression Language,Spring表達式語言)的一個重要的做用就是擴展Spring容器的功能,容許在Bean定義中使用SpEL。XML配置文件和Annotation中均可以使用SpEL。在XML和Annotation中使用SpEL時,都須要使用#{ expression }的格式來包裝表達式。java

    例若有以下的Author類:
spring

public class Author {
    private String name;
    private List<String> books;
    private Object obj;
    //省略getter 和 setter
}

    這個Author類須要注入name和books屬性。固然,能夠按照之前的方式進行配置,但若是使用SpEL,將能夠對Spring配置文件進一步簡化:
express

    由於本例要用到Spring的p命名空間和util命名空間,故先在applicationContext.xml文件的<beans>元素中增長如下內容:
app

xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd

    而後配置Bean:
spa

<!-- 使用util.priperties加載指定的資源文件 -->
<util:properties id="config" location="classpath:config_zh_CN.properties" />
<bean id="author" class="com.abc.Author">
    <!-- 在表達式中調用方法 -->
    p:name="#{'abcdef'.subString(0,3)}"
    p:obj="#{new java.lang.Object()}"
    <property name="books">
        <list>
            <!-- 在表達式中訪問其餘Bean的屬性 -->
            <value>#{config.book1}</value>
            <value>#{config.book2}</value>
            <value>#{config.book3}</value>
        </list>
    </property>
</bean>

    上面的代碼就是利用SpEL進行配置的,使用SpEL能夠在配置文件中調用方法、建立對象(這種方式能夠代替嵌套Bean語法),訪問其餘Bean的屬性等等。總之,SpEL支持的語法均可以在這裏使用,SpEL極大的簡化了Spring配置。code

相關文章
相關標籤/搜索