定义房子类(属性:面积,地址;方法:关门) 定义车子类(属性:品牌,价格;方法:行驶) 定义主人类(属性:姓名、年龄,房子、车子;方法:休息,开车) 使用两种方式实现IOC创建主人对象,并注入房子和车子属性: 1)Spring的XML配置 2)Spring的注解配置
时间: 2023-06-01 10:05:48 浏览: 124
Python 面向对象编程:类的创建与初始化、实例属性与方法、类属性与方法
好的,我明白了。以下是回答:
定义房子类:
```java
public class House {
private int area;
private String address;
public House(int area, String address) {
this.area = area;
this.address = address;
}
public void closeDoor() {
System.out.println("Closing door...");
}
// 省略 getter 和 setter 方法
}
```
定义车子类:
```java
public class Car {
private String brand;
private double price;
public Car(String brand, double price) {
this.brand = brand;
this.price = price;
}
public void drive() {
System.out.println("Driving...");
}
// 省略 getter 和 setter 方法
}
```
定义主人类:
```java
public class Owner {
private String name;
private int age;
private House house;
private Car car;
public Owner(String name, int age) {
this.name = name;
this.age = age;
}
public void rest() {
System.out.println("Resting...");
}
public void driveCar() {
car.drive();
}
// 省略 getter 和 setter 方法
}
```
使用 Spring 的 XML 配置实现 IOC:
1. 在 XML 文件中定义 bean:
```xml
<bean id="house" class="com.example.House">
<property name="area" value="100"/>
<property name="address" value="Beijing"/>
</bean>
<bean id="car" class="com.example.Car">
<property name="brand" value="Toyota"/>
<property name="price" value="200000"/>
</bean>
<bean id="owner" class="com.example.Owner">
<constructor-arg name="name" value="Tom"/>
<constructor-arg name="age" value="30"/>
<property name="house" ref="house"/>
<property name="car" ref="car"/>
</bean>
```
2. 在代码中获取 bean:
```java
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Owner owner = (Owner) context.getBean("owner");
owner.driveCar();
```
使用 Spring 的注解配置实现 IOC:
1. 在主配置类上加上注解:
```java
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
```
2. 在类中加上注解:
```java
@Component
public class House {
// 省略代码
}
@Component
public class Car {
// 省略代码
}
@Component
public class Owner {
@Autowired
private House house;
@Autowired
private Car car;
// 省略代码
}
```
3. 在代码中获取 bean:
```java
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Owner owner = (Owner) context.getBean("owner");
owner.driveCar();
```
两种方式都可以实现 IOC,具体选择哪种方式还需要根据实际场景进行分析。
阅读全文