Spring的三大核心思想:IOC(控制反转),DI(依赖注入),AOP(面向切面编程)。
(1)IOC(控制反转)
实现将组件间的关系从程序内部提到外部容器(spring的xml)来管理。
首先外部容器(spring.xml)中会动态的注册业务所需的对象(接口/类)
(2)DI(依赖注入)
组件之间的依赖关系由容器在应用系统运行期来决定, 也就是由容器动态地将某种依赖关系的目标对象实例注入到应用系统中的各个关联的组件之中
导入架包:
org.springframework
spring-beans
5.1.5.RELEASE
范例:
appliactionContext.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相当于当前bean唯一标识
class是bean 的全路径
property注入bean中的属性 必须封装
-->
<bean id="studentBean" class="com.spring.entity.StudentBean">
<property name="stu_id" value="12"/>
<property name="stu_name" value="海绵宝宝"/>
<property name="teacherBean" ref="tacherBean"/>
</bean>
<bean id="tacherBean" class="com.spring.entity.TacherBean">
<property name="tea_id" value="12"/>
<property name="tea_name" value="派大星"/>
</bean>
</beans>
}
类2:实体类
public class StudentBean {
private String stu_name;
private Integer stu_id;
private TacherBean teacherBean;
public void say(){
System.out.println("我的名字:"+this.stu_name+",年龄:"+this.stu_id);
}
}
通过获取容器注册的方法
ApplicationContext alc=new ClassPathXmlApplicationContext("applicationContext.xml");
Animal animal = (Animal) alc.getBean("printer"); //只要这里xml注入的animal变化,就可以控制不同的更改变化
animal.say();
如果注入bean时,把name值也注入进入了,那这里的值就动态变化了。
<!--注入墨盒-->
<bean id="colorink" class="cn.spring.print.ink.Colorink"></bean>
<bean id="grayink" class="cn.spring.print.ink.Grayink"></bean>
<!--纸张-->
<bean id="a4paper" class="cn.spring.print.paper.A4paper"></bean>
<bean id="b5paper" class="cn.spring.print.paper.B5paper"></bean>
<bean id="printer" class="cn.spring.print.printer.Printer">
<property name="ink" ref="colorink"/>
<property name="paper" ref="a4paper"/>
</bean>
其实DI就是IOC(控制反转)后,直接注入了其具体的数值
(3) AOP(面向切面编程)
利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。
使用"横切"技术,AOP把软件系统分为两个部分:核心关注点和横切关注点。业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是,他们经常发生在核心关注点的多处,而各处基本相似,比如权限认证、日志、事物。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点分离开来。