设计Person类和Address类, Address类,有属性 province,city Person类有name,age,address,favorite(爱好)属性,其中address属性是Address类的一个实例,favorite为列表。给出以下各个要求的配置文档和测试文档 1:请使用构造器注入,注册并创建一个(小明,21岁,福建福州,[足球、听歌、旅行])的bean实例,singleton模式: 2:请使用属性注入,注册并创建一个(小李,20岁,江苏南京,[跳舞、读书、看电影])的bean实例,prototype模式 3:请使用注解注入,注册并创建一个(小王,23岁,江西南昌,[跳舞、唱歌、旅游])的bean实例, 该实例创建时需打印出:“我创建了”,销毁前打印“我销毁了”
时间: 2023-09-23 08:12:06 浏览: 75
关于Person的类例子
配置文档如下:
```xml
<!-- 配置Person类 -->
<bean id="person" class="com.example.Person" scope="singleton">
<constructor-arg name="name" value="小明"/>
<constructor-arg name="age" value="21"/>
<constructor-arg name="address" ref="address"/>
<property name="favorite">
<list>
<value>足球</value>
<value>听歌</value>
<value>旅行</value>
</list>
</property>
</bean>
<!-- 配置Address类 -->
<bean id="address" class="com.example.Address">
<constructor-arg name="province" value="福建"/>
<constructor-arg name="city" value="福州"/>
</bean>
```
测试文档如下:
```java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// 通过读取配置文件获取 ApplicationContext 对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 通过 Bean ID 获取 singleton 类型的 bean 实例
Person person1 = (Person) context.getBean("person");
System.out.println(person1);
// 通过属性注入创建 prototype 类型的 bean 实例
Person person2 = context.getBean("person", Person.class);
person2.setName("小李");
person2.setAge(20);
Address address2 = new Address("江苏", "南京");
person2.setAddress(address2);
person2.setFavorite(Arrays.asList("跳舞", "读书", "看电影"));
System.out.println(person2);
// 通过注解注入创建 bean 实例
Person person3 = context.getBean("person", Person.class);
System.out.println(person3);
((ClassPathXmlApplicationContext) context).close();
}
}
```
Person类代码如下:
```java
import java.util.List;
public class Person {
private String name;
private int age;
private Address address;
private List<String> favorite;
public Person(String name, int age, Address address, List<String> favorite) {
this.name = name;
this.age = age;
this.address = address;
this.favorite = favorite;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", address=" + address +
", favorite=" + favorite +
'}';
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setAddress(Address address) {
this.address = address;
}
public void setFavorite(List<String> favorite) {
this.favorite = favorite;
}
// 构造函数和 setter 方法
}
```
Address类代码如下:
```java
public class Address {
private String province;
private String city;
public Address(String province, String city) {
this.province = province;
this.city = city;
}
@Override
public String toString() {
return "Address{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
'}';
}
// 构造函数和 getter 方法
}
```
阅读全文