原文链接:https://blog.csdn.net/kingyxfly/article/details/79826333
1.spring: 创建Bean和维护Bean之间的关系
IOC(控制反转/依赖注入)、AOP(面向切面编程)
2.AOP:
这种在运行时,动态的将代码切入到类的指定方法、指定位置的编程思想。
3.反射:在spring-config.xml中的id->class,找到文件类
4.
以下为链接内容:
小汽车类Car
package com.example;
public class Car {
private String name;
private double price;
// 省略getter,setter
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
public void carInfo() {
System.out.println("i have this car: " + name);
}
}
汽车拥有者类:Person
package com.example;
public class Person {
private String name;
private int age;
private Car car;
// 省略getter,setter
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", car=" + car +
'}';
}
}
Spring配置文件spring-config.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="car" class="com.example.Car">
<property name="name" value="hongqi"/>
<property name="price" value="1000000.0"/>
</bean>
<bean id="person" class="com.example.Person">
<property name="name" value="zhaangsan"/>
<property name="age" value="27"/>
<property name="car" ref="car"/>
</bean>
</beans>
测试类SpringMain
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringMain {
public static void main(String[] args) {
// 创建IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
// 通过getBean获取Car的实例,这里利用了反射
Car car = (Car) context.getBean("car");
car.carInfo();
System.out.println(car.toString());
Person person = (Person) context.getBean("person");
System.out.println(person.toString());
}
}
执行结果:
i have this car: hongqi
Car{name='hongqi', price=1000000.0}
Person{name='zhaangsan', age=27, car=Car{name='hongqi', price=1000000.0}}