(六)Spring表达式语言SpEl

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fangxinde/article/details/78286131

第一步: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=金领]

猜你喜欢

转载自blog.csdn.net/fangxinde/article/details/78286131