SpEL(3)

来源:互联网 发布:matlab矩阵diff 编辑:程序博客网 时间:2024/05/16 23:39

SpEL支持在Bean定义时注入,默认使用“#{SpEL表达式}”,其中“#root”默认可以认为是ApplicationContext,获取根对象属性其实是获取容器中的bean

XML方式

applicationContext.xml

       <bean id="bean1" class="java.lang.String">       <constructor-arg value="#{'hello'}"></constructor-arg>       </bean>       <bean id="bean2" class="java.lang.String">       <constructor-arg value="#{' world!'}"></constructor-arg>       </bean>       <bean id="bean3" class="java.lang.String">       <constructor-arg value="#{'hello'+@bean2}"></constructor-arg>             </bean>

SpELByXmlTest .java

public class SpELByXmlTest {    @Testpublic void test(){    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");    String bean1=ctx.getBean("bean1",String.class);    String bean2=ctx.getBean("bean2",String.class);    String bean3=ctx.getBean("bean3",String.class);    System.out.println(bean1);    System.out.println(bean2);    System.out.println(bean3);}}

注解方式

Spring使用@Value注解来指定SpEL表达式,该注解可以放到字段、方法以及方法参数上

SpELBean .java

package com.SpEL.bean;import org.springframework.beans.factory.annotation.Value;public class SpELBean {    @Value("#{'hello'+@bean2}")private String msg;    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }}

application.xml

       <context:annotation-config/>       <bean id="SpELBean" class="com.SpEL.bean.SpELBean">             </bean>       <bean id="SpELBean2" class="com.SpEL.bean.SpELBean">       <property name="msg" value="#{@bean1}"></property>             </bean>

SpELByXmlTest .java

public class SpELByXmlTest {    @Testpublic void test(){    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");    SpELBean SpELBean=ctx.getBean("SpELBean",com.SpEL.bean.SpELBean.class);    SpELBean SpELBean2=ctx.getBean("SpELBean2",com.SpEL.bean.SpELBean.class);    System.out.println(SpELBean.getMsg());    System.out.println(SpELBean2.getMsg());}}

由上面例子可以知道stter注入的值会覆盖@Value的值

0 0