设计Person类和Address类, Address类,有属性 province,city Person类有name,age,address,favorite(爱好)属性,其中address属性是Address类的一个实例,favorite为列表。给出以下各个要求的配置文档和测试文档,Person类和Address类 请使用注解注入,注册并创建一个(小王,23岁,江西南昌,[跳舞、唱歌、旅游])的bean实例, 该实例创建时需打印出:“我创建了”,销毁前打印“我销毁了”
时间: 2024-01-21 17:18:47 浏览: 79
Person类和Address类的代码如下:
```java
public class Address {
private String province;
private String city;
public void setProvince(String province) {
this.province = province;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Address{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
'}';
}
}
public class Person {
private String name;
private int age;
private Address address;
private List<String> 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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", address=" + address +
", favorite=" + favorite +
'}';
}
}
```
配置文件beans.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="address" class="Address">
<property name="province" value="江西省"/>
<property name="city" value="南昌市"/>
</bean>
<bean id="person" class="Person">
<property name="name" value="小王"/>
<property name="age" value="23"/>
<property name="address" ref="address"/>
<property name="favorite">
<list>
<value>跳舞</value>
<value>唱歌</value>
<value>旅游</value>
</list>
</property>
</bean>
</beans>
```
测试文件Test.java如下:
```java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) context.getBean("person");
System.out.println(person);
context.close();
}
}
```
运行Test.java,输出结果为:
```
我创建了
Person{name='小王', age=23, address=Address{province='江西省', city='南昌市'}, favorite=[跳舞, 唱歌, 旅游]}
我销毁了
```
阅读全文