实验1:定义学生类Student,其属性有姓名、出生年月(datetime)、年龄、性别爱好(list每个人有多个爱好),请利用Spring容器,来完成Student对象|够利用构造注入和Set注入的方式为其属性赋值。写出测试程序。
时间: 2024-09-14 22:09:06 浏览: 67
首先,我们需要定义一个学生类 `Student`,并包含姓名、出生年月、年龄和性别爱好等属性。在Spring框架中,可以通过构造注入和setter注入两种方式为这个类的属性赋值。以下是一个简单的例子:
1. 定义Student类:
```java
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
public class Student {
private String name;
private Date birthDate;
private int age;
private String gender;
private List<String> hobbies;
public Student() {
// 默认构造函数
}
// 构造函数注入
public Student(String name, Date birthDate, int age, String gender, List<String> hobbies) {
this.name = name;
this.birthDate = birthDate;
this.age = age;
this.gender = gender;
this.hobbies = hobbies;
}
// Set注入的setter方法
public void setName(String name) {
this.name = name;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public void setAge(int age) {
this.age = age;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
// Getter方法和toString方法用于测试
// ...
}
```
2. 定义Spring配置文件 `applicationContext.xml`:
```xml
<?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="studentByConstructor" class="Student">
<constructor-arg value="张三"/>
<constructor-arg>
<date>1998-01-01</date>
</constructor-arg>
<constructor-arg value="25"/>
<constructor-arg value="男"/>
<constructor-arg>
<list>
<value>阅读</value>
<value>编程</value>
</list>
</constructor-arg>
</bean>
<!-- Set注入 -->
<bean id="studentBySetter" class="Student">
<property name="name" value="李四"/>
<property name="birthDate">
<date>1999-02-02</date>
</property>
<property name="age" value="24"/>
<property name="gender" value="女"/>
<property name="hobbies">
<list>
<value>旅游</value>
<value>画画</value>
</list>
</property>
</bean>
</beans>
```
3. 编写测试程序:
```java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringDI {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 构造注入测试
Student studentByConstructor = (Student) context.getBean("studentByConstructor");
System.out.println("构造注入的姓名:" + studentByConstructor.getName());
// Set注入测试
Student studentBySetter = (Student) context.getBean("studentBySetter");
System.out.println("Set注入的姓名:" + studentBySetter.getName());
}
}
```
以上程序中,我们定义了两个bean,一个是通过构造函数注入属性,另一个是通过setter方法注入属性。然后在测试程序中,我们通过Spring容器获取这两个bean,并打印出通过不同注入方式设置的姓名属性,从而验证属性是否正确注入。
阅读全文