SpEL(3)

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 {
    @Test
public 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 {
    @Test
public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值