Spring入门三(EL表达式)

1.EL表达式:能够在运行时构建复杂表达式,存取对象属性、对象方法调用等。格式为:#{表达式}
通过xml方式:


通过Annotation的方式(部分代码):
@Component("tea") public class Teacher { @Value("王老师")//属性的值会注入进去 private String name; @Value("30") private int age;

@Component("stu") public class Student { @Value("张三") private String name; @Value("20") private int age; @Value("M") private char sex; @Value("#{tea}")//用到了EL表达式,也可以用tea中的属性。#{tea.name},但是私有属性必须提供get方法。 private Teacher teacher;

EL表达式中可以运行函数,并将运行的结果的值注入到属性中去:
@Component("stu") public class Student { @Value("#{'ZHANGSAN'.toLowerCase()}")//转为小写后进行注入 private String name; @Value("20") private int age;

运行结果:
Student{name='zhangsan', age=20, sex=M, teacher=Teacher{name='王老师', age=30}}

EL表达式中还支持算数、关系、逻辑和三目运行。可以写在注释中,也可以写在xml文件中。
@Value("#{12+12}") private int age;

EL表达式取出集合中的值进行注入:
@Component("pojo") public class POJO { @Value("#{arr.list[1]}")//使用EL表达式,也可以放到配置文件中 private String listValue; @Value("#{arr.map['name']}")//通过key取出value private String mapvalue; @Override public String toString() { return "POJO{" + "listValue='" + listValue + '\'' + ", mapkey='" + mapvalue + '\'' + '}'; } public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml"); POJO p=(POJO) context.getBean("pojo"); System.out.println(p); } }

xml中的部分代码:
zhangsan 20

运行结果:
POJO{listValue='https://www.it610.com/article/20', mapkey='zhangsan'}

【Spring入门三(EL表达式)】EL表达式还有可以写成${},和#{}的区别是后者会加单引号,前者不会。
结论:spring容器可以同时由注释和配置文件进行控制。


上一篇 ---The End--- 下一篇

    推荐阅读