个人读书笔记,题外话都写在第1章https://blog.csdn.net/u013652550/article/details/119800308。
第2章主要带我们了解了Spring框架的概念,并初步认识了IOC、AOP。
2.1 Spring框架介绍
以下仅为罗列,仅供全部学完后复习回忆用。
核心容器:
spring-core + spring-beans = spring-context,提供IOC(控制反转)和依赖注入(DI)。
spring-context-support为集成第三方库提供支持。
spring-expression提供表达式语言。
AOP:
spring-aop提供了一个AOP实现。
spring-aspects集成AspectJ。
spring-instrument提供一些工具。
消息发送:
spring-messaging(自Spring4开始)。
数据访问/集成:
spring-jdbc:JDBC模块。
spring-orm:ORM模块。
spring-oxm:OXM模块。
spring-jms:JMS模块。
spring-tx:事务模块。
Web:
spring-web:提供基本特性。
spring-webmvc:包含Spring的MVC和REST Web Service实现。
spring-webflux:一个新的非堵塞函数式Reactive Web框架。
测试:
spring-test:支持Spring组件JUnit和TestNG的单元测试和集成测试。
2.2 依赖注入DI与控制反转IOC
使用@Component将类注解成组件,使用@Autowired将IAir类型对象注入Person中,使用@Qualifier关键字来进行区分。新建ApplicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example.airdemo"/>
</beans>
context:component-scan表明使用注解,这里暂不列举bean的XML配置。顺便列举一下Spring Boot的5种读取配置方式:https://blog.csdn.net/weixin_39220472/article/details/80194899
1.直接读取bean。
2.通过config读取指定文件。
3.通过application.properties读取。
4.通过application.yml读取。
5.通过applicationContext.xml读取。
2.3 面向切面编程
AOP实际上是由目标类的代理类实现的。代理模式又分为动态代理模式和静态代理模式。
静态代理
静态代理关键是在代理对象和目标对象实现共同的接口,并且代理对象持有目标对象的引用。可以通过在代理类的构造方法中传入目标对象作为成员变量实现。
动态代理
关键有如下两点:
代理类必须实现InvocationHandler接口及其中的invoke(Object proxy, Method method, Object[] args)方法。参数分别为:目标对象、方法、方法参数列表。Spring会自动调用该方法,方法体内需调用method.invoke(Object obj, Object...args)进行实际执行,参数分别为:目标对象、方法参数列表。具体来说,第一个参数应事先已设置过(参考静态代理),所以并不需要Spring调用invoke提供的Object参数。一般返回欲执行方法的实际返回值,但亦可将目标对象返回。
调用Proxy.newProxyInstance(ClassLoader classLoader, Class<?>[] interfaces, InvocationHandler h)方法生成动态代理对象。参数分别为:目标对象类加载器、目标对象接口列表、关联对象。参考静态代理,获取传入目标对象的Class类并通过getter方法填写前两个参数,第三个参数一般填写自身this。
package com.example.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynaProxyServiceA implements InvocationHandler {
private Object target;
public Object bind(Object object) {
target = object;
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method:" + method);
System.out.println("args:" + args);
System.out.println("target:" + target);
System.out.println("log start");
Object result = method.invoke(target, args);
System.out.println("log end");
return result;
}
}