前面的知识点 忘记的 参考
https://blog.csdn.net/weixin_44822455/article/details/108933150
Spring注解开发
1.1bean和属性注入
1 引入context约束
在xml文件中引入改文件即可
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">//上面在原来的spring xml文件中添加 context相关//这里配置需要扫描的包位置<context:component-scan base-package="com.pojo"></context:component-scan><context:annotation-config></context:annotation-config></beans>
2 编写实体类
//这里component相当于 <bean id="user" class="com.pojo.user">@Component("user")public class User {//可以通过value直接实现注入@Value("小明")public String name ="zzz";}
3 测试
public static void main(String[] args) {ApplicationContext ct = new ClassPathXmlApplicationContext("spring-01.xml");User user = (User)ct.getBean(User.class);System.out.println(user.name);}
2.Component衍生注解
我们这些注解,就是替代了在配置文件当中配置步骤而已!更加的方便快捷!
@Component三个衍生注解
为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。
- @Controller:web层
- @Service:service层
- @Repository:dao层
3.小结
XML与注解比较
- XML可以适用任何场景 ,结构清晰,维护方便
- 注解不是自己提供的类使用不了,开发简单方便
xml与注解整合开发 :推荐最佳实践
- xml管理Bean
- 注解完成属性注入
- 使用过程中, 可以不用扫描,扫描是为了类上的注解
作用:
- 进行注解驱动注册,从而使注解生效
- 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
- 如果不扫描包,就需要手动配置bean
-
代理模式
静态代理
静态代理角色分析
抽象角色 : 一般使用接口或者抽象类来实现
- 真实角色 : 被代理的角色
- 代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .
- 客户 : 使用代理角色来进行一些操作 .
代码实现
1.创建出租的接口
//抽象角色 :租房public interface Rent {public void rent();}
2.创建 房东,可以出租房子
//真实角色:房东,房东要出租房子public class Host implements Rent {@Overridepublic void rent() {System.out.println("房屋出租");}}
3.创建中介,代理房东出租房子,并且添加一些新的服务
public class Proxy implements Rent {private Host host;public Proxy(){}public Proxy(Host host){this.host = host;}//租房@Overridepublic void rent() {seeHouse();host.rent();fare();}//看房public void seeHouse(){System.out.println("带房客看房");}//收中介费public void fare(){System.out.println("收中介费");}}
4.创建客户类,进行买房子
public class Clinet {public static void main(String[] args) {//房东要租房Host host = new Host();//中介帮助房东Proxy proxy = new Proxy(host);//你去找中介!proxy.rent();}}
静态代理的好处
- 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
- 公共的业务由代理来完成 . 实现了业务的分工 ,
- 公共业务发生扩展时变得更加集中和方便 .
缺点 :
- 类多了 , 多了代理类 , 工作量变大了 . 开发效率降低 .
我们想要静态代理的好处,又不想要静态代理的缺点,所以 , 就有了动态代理 !
静态代理理解:在不动原来代码的基础上,需要增添新的业务,来实现功能拓展。
场景带入:若要在原有代码基础上,增添新的功能(添加日志功能),要求不改动原来代码
代码实现
1.创建接口
public interface UserService {void add();void delete();void update();void select();}
2.创建原来代码
public class UserServiceImpl implements UserService {@Overridepublic void add() {System.out.println("添加了一个用户");}@Overridepublic void delete() {System.out.println("删除了一个用户");}@Overridepublic void update() {System.out.println("更改了一个用户");}@Overridepublic void select() {System.out.println("查找了一个用户");}}
3.创建代理类,代理类 代理原来代码所需要实现功能,并增加日志功能
public class UserServiceProxy implements UserService {UserService userService = new UserServiceImpl();public void setUserService(UserServiceImpl userService){this.userService = userService ;}@Overridepublic void add() {log("add");userService.add();}@Overridepublic void delete() {userService.delete();}@Overridepublic void update() {userService.update();}@Overridepublic void select() {userService.select();}public void log(String msg){System.out.println("[Debug] 使用了"+msg+"方法");}}
4.客户实现类
public class Client {public static void main(String[] args) {UserServiceProxy userServiceProxy = new UserServiceProxy();UserServiceImpl userService = new UserServiceImpl();userServiceProxy.setUserService(userService);userServiceProxy.add();}}
动态代理
- 动态代理的角色和静态代理的一样 .
- 动态代理的代理类是动态生成的 . 静态代理的代理类是我们提前写好的
- 动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理
- 基于接口的动态代理——JDK动态代理
- 基于类的动态代理—cglib
- 现在用的比较多的是 javasist 来生成动态代理 . 百度一下javasist
- 我们这里使用JDK的原生代码来实现,其余的道理都是一样的!
需要了解2个类
JDK的动态代理需要了解两个类
核心 : InvocationHandler 和 Proxy , 打开JDK帮助文档看看
【InvocationHandler:调用处理程序】
Object invoke(Object proxy, 方法 method, Object[] args);
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。
【Proxy : 代理】


//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(),this);
}
代码实现
还是以房屋出租为例子
1.房东类
public class Host implements Rent {@Overridepublic void rent() {System.out.println("房屋出租");}}
2.代理类
public class ProxyInvocationHandler implements InvocationHandler {private Rent rent;public void setRent(Rent rent){this.rent = rent;};//生成代理类,重点是第二个参数,获取要代理的抽象角色!之前都是一个角色,现在可以代理一类角色public Object getProxy(){return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);}// proxy : 代理类 method : 代理类的调用处理程序的方法对象.// 处理代理实例上的方法调用并返回结果@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {seeHouse();//核心:本质利用反射实现!Object result = method.invoke(rent, args);fare();return result;}//看房public void seeHouse(){System.out.println("带房客看房");}//收中介费public void fare(){System.out.println("收中介费");}}
3.客户实现类(测试类)
public class Client {public static void main(String[] args) {//真实角色Host host = new Host();//代理实例的调用处理程序ProxyInvocationHandler pih = new ProxyInvocationHandler();pih.setRent(host); //将真实角色放置进去!Rent proxy = (Rent)pih.getProxy(); //动态生成对应的代理类!proxy.rent();}}
将代理类抽象 变成代理工具类 ```java public class ProxyInvocationHandler implements InvocationHandler { private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成代理类 public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
// proxy : 代理类 // method : 代理类的调用处理程序的方法对象. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());Object result = method.invoke(target, args);return result;
}
public void log(String methodName){
System.out.println("执行了"+methodName+"方法");
}
}
测试类```javapublic class Test {public static void main(String[] args) {//真实对象UserServiceImpl userService = new UserServiceImpl();//代理对象的调用处理程序ProxyInvocationHandler pih = new ProxyInvocationHandler();pih.setTarget(userService); //设置要代理的对象UserService proxy = (UserService)pih.getProxy(); //动态生成代理类!proxy.delete();}}
动态代理好处
静态代理有的它都有,静态代理没有的,它也有!
- 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
- 公共的业务由代理来完成 . 实现了业务的分工 ,
- 公共业务发生扩展时变得更加集中和方便 .
- 一个动态代理 , 一般代理某一类业务
-
AOP
定义
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP在Spring中的作用
提供声明式事务;允许用户自定义切面

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即 Aop 在 不改变原有代码的情况下 , 去增加新的功能 .AOP的使用
代码实现
1.导入依赖<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version></dependency>
2.创建业务接口和业务类 ```java public interface UserService {
public void add();
public void delete();
public void update();
public void search();
}
业务实现类```javapublic class UserService2 implements com.service.UserService2 {@Overridepublic void add() {System.out.println("实现添加方法");}@Overridepublic void delete() {System.out.println("实现删除方法");}@Overridepublic void update() {System.out.println("实现更新方法");}@Overridepublic void select() {System.out.println("实现查找方法");}}
3.配置文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd">//这里要留意新添加的aop引用文件<!-- 注册bean--><bean id="userService" class="com.service.Impl.UserService2"></bean><bean id="diy" class="com.util.DiyPointcut"></bean><!-- 配置AOP--><aop:config><!-- 配置切入点--><!-- 这里expression代码规范是这样的--><aop:pointcut id="pointcut" expression="execution(* com.service.UserService2.*(..))"/><!-- 配置切入面--><!-- 这里ref代表准备要切入的类和方法--><aop:aspect ref="diy"><aop:before pointcut-ref="pointcut" method="before"/><aop:after pointcut-ref="pointcut" method="after"/></aop:aspect></aop:config></beans>
4.测试类
@Testpublic void test02(){ApplicationContext context = new ClassPathXmlApplicationContext("spring-aop02.xml");UserService2 userService = (UserService2) context.getBean("userService");userService.add();}//结果入下//---------方法执行前---------//实现添加方法//---------方法执行后---------
AOP注解使用
代码实现
1.创建接口和实现类
public interface UserService {public void doSth();}
实现类
@Servicepublic class UserServiceImpl implements UserService {@Overridepublic void doSth() {System.out.println("开启业务");}}
2.要注入的一些其他方法类
//这里也要使用Component将 方法类托管给Spring容器,同时也要用注解Aspect标注切面类@Component@Aspectpublic class MyAspect {//**这里可以使用定义切点方式(补充)@Pointcut("execution(* com.demo02.UserServiceImpl.do*(..))")public void pointcut1(){//这里不需要写东西}//之后@Before("pointcut1()")//这里代表是切面 执行于切点前还是切点后 其他方法类似 (固定写法)@Before("execution(* com.demo02.UserServiceImpl.do*(..))")public void before(){System.out.println("=======业务前注入======");}}
3.配置类
//扫描spring相关类 和包//开启注解允许//标注这是配置类@Configuration@EnableAspectJAutoProxy@ComponentScan("com.demo02")public class Myconfig {}
4.测试类
public class MyTest {@Testpublic void test07(){ApplicationContext context = new AnnotationConfigApplicationContext(Myconfig.class);// 这里需要注意 需要获得的是 接口.class 而不是实现类UserService bean = context.getBean(UserService.class);bean.doSth();}}
测试结果
=======业务前注入======开启业务
