public class Student { //学生实体类 private String name; //姓名 private Integer age; //年龄 private Grade grade; //年级 @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", grade=" + grade + "]"; } public Student() { super(); } public Student(String name, Integer age, Grade grade) { super(); this.name = name; this.age = age; this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } //根据年龄的不同返回age不同的值 public Integer changeAge(){ return (this.age>25)?20:this.age; } }
public class Grade { //年级实体类 private String name; //年级名称 @Override public String toString() { return "Grade [name=" + name + "]"; } public Grade() { super(); } public Grade(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2.创建对应的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- spel 注入 spring el表达式 需要实体类中 有对应的get() 第一个学生 --> <bean id="student1" class="cn.bdqn.bean.Student"> <property name="name" value="小黑"/> <property name="age" value="#{T(java.lang.Math).random()*50}"/> </bean> <!-- 第二个学生 name属性值 是 第一个学生的 age值 是方法中获取的 --> <bean id="student2" class="cn.bdqn.bean.Student"> <property name="name" value="#{student1.name}"/> <!-- <property name="age" value="#{student1.age>30?25:student1.age}"/> --> <!--直接把年龄的判断写在类中 并且得到返回值 --> <property name="age" value="#{student1.changeAge()}"/> </bean> <!--匿名内部bean 年级只属于指定的Student --> <!-- <bean id="student" class="cn.bdqn.bean.Student"> <property name="name" value="小黑"/> <property name="age" value="50"/> <property name="grade"> 其他的bean中 无法访问 <bean id="grade" class="cn.bdqn.bean.Grade" p:name="1年级"/> </property> </bean> --> </beans>
3.创建测试类
public class StudentTest { //使用spel注入 @Test public void test01(){ ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); Student student1=(Student) context.getBean("student1"); Student student2=(Student) context.getBean("student2"); System.out.println("student1信息:"+student1); System.out.println("student2信息:"+student2); } //匿名内部bean @Test public void test02(){ ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); Student student=(Student) context.getBean("student"); System.out.println("student信息:"+student); } }