(六)Spring表達式語言SpEl

第一步:xml文件中配置bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="address" class="com.atguigu.spring.beans.spel.Address">
    <!-- 使用spel爲屬性賦一個字面值 -->
        <property name="city" value="#{'BeiJing'}"></property>
        <property name="street" value="WuDaoKou"></property>
    </bean>
    <bean id="car" class="com.atguigu.spring.beans.spel.Car">
        <property name="brand" value="Audi"></property>
        <property name="price" value="800000"></property>
        <property name="tyrePerimeter" value="#{T(java.lang.Math).PI*80}"></property>
    </bean>
    <bean id="person" class="com.atguigu.spring.beans.spel.Person">
        <!--使用spel來應用其他的Bean  -->
        <property name="car" value="#{car}"></property>
        <!--使用spel來應用其他的Bean 的屬性 -->
        <property name="city" value="#{address.city}"></property>
        <!--使用spel中使用運算符-->
        <property name="info" value="#{car.price>300000?'金領':'白領'}"></property>
        <property name="name" value="fangxinde"></property>
    </bean>
</beans>

第二步:運行main方法

package com.atguigu.spring.beans.spel;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-spel.xml");
         Address address=(Address) ctx.getBean("address");
         System.out.println(address);
         Car car=(Car) ctx.getBean("car");
         System.out.println(car);
         Person person=(Person) ctx.getBean("person");
         System.out.println(person);
    }
}

第三步:運行結果
Car’s Constructor…..
Address [city=BeiJing, street=WuDaoKou]
Car [brand=Audi, price=800000.0, tyrePerimeter=251.32741228718345]
Person [name=fangxinde, car=Car [brand=Audi, price=800000.0, tyrePerimeter=251.32741228718345], city=BeiJing, info=金領]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章