spring学习

1、spring

1.1、优点

  • Spring是一个开源的免费的框架 (容器)!
  • Spring是一个轻量级的、非入侵式的框架!
  • 控制反转 (IOC) ,面向切面编程 (AOP) !
  • 支持事务的处理,对框架整合的支持!

spring就是一个轻量级的控制反转 (IOC) 和面向切面编程 (AOP) 的框架!

1.2、组成

在这里插入图片描述

2、IOC理论推导

在传统的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码! 如果程序代码量十分大,修改一次的成本代价十分昂贵!

我们使用一个Set接口实现,已经发生了革命性的变化!

private UserMapper userMapper;
//利用set进行动态实现值的注入!
public void setuserMapper(userMapper userMapper) {
	this.userMapper = userMapper;
}
  • 之前,程序是主动创建对象(new 的方式)!控制权在程序猿手上!
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!

这种思想,从本质上解决了问题,我们程序猿不用再去管理对象的创建了。系统的耦合性大大降低,可以更加专注的在业务的实现上!这是IOC 的原型!

IOC本质

控制反转IOC(lnversion of Control),是一种设计思想,DI(依赖注入)是实现loC的方法之一。 没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了(对象交给IOC容器管理)。

在这里插入图片描述
在这里插入图片描述
lOC是Spring框架的核心内容,使用多种方式完美的实现了loC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现loC。
Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从loc容器中取出需要的对象。
在这里插入图片描述
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是loC容器,其实现方法是依赖注入 (Dependency Injection,DI)。

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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->
</beans>

3、helloSpring

1、导入依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>6.0.0</version>
</dependency>

2、创建类HelloWorld和ShowHello

public class HelloWorld {
	String name;
	public void setName(){
		this.name = name;
	}
	public void sayHello(){
		System.out.println("Hello"+name);
	}
}
public class ShowHello {
	//定义HelloWorld对象作为属性,并提供set方法
	HelloWorld hw;
	public void setHw(HelloWorld hw) {
		this.hw = hw;
	}
	public void show(){
		hw.sayHello();
	}
}

3、编写配置文件applicationContext.xml
在配置文件中,通过bean标签来管理对象,并通过property标签指定属性的值

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

	<!--创建Bean组件,有指定的id,对应的class
	一个bean相当于new 一个该类的对象
	-->
	<bean id="helloWorld" class="com.spring.demo02.HelloWorld">
		<!-- 设置该类属性的值 -->
		<property name="name" value="Spring"/>
	</bean>

	<bean id="showHello" class="com.spring.demo02.ShowHello">
		<!-- 指定该类属性所对应的bean 即将helloWorld对象注入-->
		<property name="hw" ref="helloWorld"></property>
	</bean>
</beans>

4、Main测试

public static void main(String[] args) {
	//通过配置文件得到bean组件
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	ShowHello sw = (ShowHello)ac.getBean("showHello");
	sw.show();
}

这个过程就叫控制反转

  • 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
  • 反转:程序本身不创建对象,而变成被动的接收对象 依赖注入:就是利用set方法来进行注入的. IOC是一种编程思想,由主动的编程变成被动的接收

OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的loC,一句话搞定 : 对象由Spring 来创建,管理,装配 !

4、IOC创建对象的方式

  • 默认使用无参构造函数的方式创建对象
  • 使用有参的构造函数创建对象,需要使用标签constructor-arg实现

1、构造函数参数的下标赋值

	<bean id="helloWorld" class="com.spring.demo02.HelloWorld">
		<!-- index参数的顺序 -->
		<constructor-arg index="0" value="Spring"/>
		.......
	</bean>

2、构造函数参数的类型

	<bean id="helloWorld" class="com.spring.demo02.HelloWorld">
		<!-- type参数的类型 -->
		<constructor-arg type="java.lang.String" value="Spring"/>
	</bean>

3、构造函数参数的参数名

	<bean id="helloWorld" class="com.spring.demo02.HelloWorld">
		<!-- name参数名 -->
		<constructor-arg name="name" value="Spring"/>
		......
	</bean>

总结:spring framework框架在配置文件加载的时候,容器中管理的对象就已经初始化了!

5、Spring配置

5.1、别名

可以给注册的对象起别名

<alias name="fromName" alias="toName"/>

5.2、bean

	<!--创建Bean组件,有指定的id,对应的class
	一个bean相当于new 一个该类的对象
	name可以给对象起多个别名,可以使用空格,逗号,分号等分隔
	-->
	<bean id="helloWorld" class="com.spring.demo02.HelloWorld" name="hello hello2,hello3">
		<!-- 设置该类属性的值 -->
		<property name="name" value="Spring"/>
	</bean>

5.3、import

import可以合并多个配置文件

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
	<import resource="beans1.xml" />
	<import resource="beans2.xml" />
	<import resource="beans3.xml" />
</beans>

6、依赖注入

6.1、构造器注入

参考前面第4章

6.2、Set注入

  • 依赖:对象由容器创建
  • 注入:对象的属性由容器的设置

测试类

//偷懒使用lombok创建get、set方法
@Data 
public class TestDependence() {
	private String name;
	private HelloWorld hello;
	private List<String> list;
	private Map<String, String> map;
	private String[] strings;
	private Set<String> set;
	private Properties info;
}
<bean id="testDependence" class="com.TestDependence">
  <!-- 数值注入 -->
  <property name="name" value="hello world!" />

  <!-- null注入 -->
  <property name="name" >
	  <null/>
  </property>
  	  
  <!-- 对象注入 -->
  <property name="hello" ref="helloWorld"></property>	

  <!-- 数组 -->
  <property name="strings">
	  <array>
		  <value>a</value>
		  <value>b</value>
		  <value>c</value>
	  </array>
  </property>
  
  <!-- properties -->
  <property name="info">
	  <props>
		  <prop key="administrator">administrator@example.org</prop>
		  <prop key="support">support@example.org</prop>
		  <prop key="development">development@example.org</prop>
	  </props>
  </property>
  
  <!-- List -->
  <property name="list">
	  <list>
		  <value>a list element followed by a reference</value>
		  //注入id为myDataSource的对象
		  <ref bean="myDataSource" />
	  </list>
  </property>
  
  <!-- map -->
  <property name="map">
	  <map>
		  <entry key="an entry" value="just some string"/>
		  <entry key="a ref" value-ref="myDataSource"/>
	  </map>
  </property>
  
  <!-- set -->
  <property name="set">
	  <set>
		  <value>just some string</value>
		  <ref bean="myDataSource" />
	  </set>
  </property>
</bean>

6.3、扩展方式注入

6.3.1、p命名空间( p-namespace)

要使用p-namespace必须要在配置文件中引入xml约束
xmlns:p=“http://www.springframework.org/schema/p”

<?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:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd">
  
  <!-- p命名空间注入,可以直接注入属性的值: property -->
  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close"
  p:driverClassName="com.mysql.jdbc.Driver"
  p:url="jdbc:mysql://localhost:3306/mydb"
  p:username="root"
  p:password="misterkaoli"/>
</beans>

6.3.2、c命名空间(c-namespace)

注意:要使用c-namespace必须要在配置文件中引入xml约束
xmlns:c=“http://www.springframework.org/schema/c”
类必须拥有无参构造函数,至少一个有参构造函数

<?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:c="http://www.springframework.org/schema/c"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd">
  
  <!-- c命名空间注入,通过构造器注入: construct-args -->
	<bean id="beanTwo" class="x.y.ThingTwo"/>
	  <bean id="beanThree" class="x.y.ThingThree"/>
	  <!-- traditional declaration with optional argument names -->
	  <bean id="beanOne" class="x.y.ThingOne">
	  <constructor-arg name="thingTwo" ref="beanTwo"/>
	  <constructor-arg name="thingThree" ref="beanThree"/>
	  <constructor-arg name="email" value="something@somewhere.com"/>
	  </bean>
	  <!-- c-namespace declaration with argument names -->
	  <bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo"
	  c:thingThree-ref="beanThree" c:email="something@somewhere.com"/>
	</beans>

6.4 bean的作用域

在这里插入图片描述
1、单例模式(Spring默认)

<bean id="accountService" class="com.something.DefaultAccountService"
scope="singleton"/>

2、原型模式:每次从容器中get对象,都是一个新的对象

<bean id="accountService" class="com.something.DefaultAccountService"
scope="prototype"/>

3、其他的request、session、application是web开发中使用的

7、Bean的自动装配

  • 自动装配是Spring满足bean依赖一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring中有三种装配的方式:
1.在xml中显示的配置
2.在java中显示配置
3.隐式的自动装配bean【重要

7.1 byName

<!-- 
	byName: 会自动在容器上下文中查找,
	和自己对象set方法后面的值对应的 beanid
	注意:需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
-->
<bean id="people"class="com.pojo.People” autowire="byName">
	<property name="name” value="张三"/>
</bean>

7.2 byType

<!-- 
	byType: 会自动在容器上下文中查找,
	和自己对象属性类型相同的bean
	注意:需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
-->
<bean id="people"class="com.pojo.People” autowire="byType">
	<property name="name” value="张三"/>
</bean>

7.3、使用注解实现自动装配

要使用注解:
1.导入约束
2.配置注解的支持

<?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
  https://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  https://www.springframework.org/schema/context/spring-context.xsd">
  <context:annotation-config/>
</beans>

@Autowired
直接在属性上使用即可!也可以在set方式上使用!

使用Autowired 我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring) 容器中存在,且符合名字byname!

@Nullable   字段标记了这个注解,说明这个字段可以为nu11;
public @interface Autorwired {
	//如果显示定义了Autowired的required属性为false,说明这个对象可以为nu11,否则不允许为空
	boolean required() default true;
}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解 [@Autowired] 完成的时候、我们可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!

public class People {
	@Autowired
	@Qualifier(value="cat111")
	private Cat cat;
	
	@Autowired
	@Qualifier(value="dog222")
	private Dog dog;
	private string name;
}

@Resource注解

public class People {
	@Resource(name = "cat1")
	private Cat cat;
	
	@Autowired
	private Dog dog;
	private string name;
}

@Resource 和@ Autowired 的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @ Autowired 通过byType的方式实现,而且必须要求这个对象存在! [常用]
  • @ Resource 默认通过byname的方式实现,如果找不到名字,则通过byType实现! 如果两个都找不到的情况下,就报错! [常用]
  • 执行顺序不同: @ Autowired 通过byType的方式实现。@ Resource 默认通过byname的方式实现。

8、使用注解开发

注意:
1、spring4之后要使用注解开发必须确定导入aop的包
2、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
  https://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  https://www.springframework.org/schema/context/spring-context.xsd">

  <!-- 指定要扫描的包,这个包下的注解就会生效-->
  <context:component-scan base-package="com.pojo"/>
  <context:annotation-config/>
</beans>

1、属性注入

//相当于 <bean id="user" class="com.User"/>
@Component
public class User {
	public String name;
	//相当于 <property name="name value=""/>
	@Value("")
	public void setName(String name) {
		this.name = name;
	}
}

2、衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!

  • Mapper [@Repository]
  • service [@Service]
  • controller [@Controller]

3、自动装配

- @Autowired :自动装配通过类型。名字
    如果Autowired不能唯一自动装配上属性,则需要通过
- @Qualifier(value="xxx")
- @Nullable 字段标记了这个注解,说明这个字段可以为nu11;
- @Resource :自动装配通过名字,类型。

4、作用域

@Scope("prototype")

5、xml与注解最佳实践:

  • xml 用来管理bean;
  • 注解只负责完成属性的注入;
  • 我们在使用的过程中,只需要注意一个问题: 必须让注解生效,就需要开启注解的支持

9、使用java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig 是Spring的一个子项目,在Spring 4之后,它成为了一个核心功能!

实体类

//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中@Component
public class User {
	private String name;
	public String getName() {
		return name;
	}
	@Value("QINJIANG") //属性注入值
	public void setName(String name) {
		this.name = name;
	}
}

配置类

package com.kuang.config;

import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Componentscan;
import org.springframework.context.annotation,Configuration;
import org.springframework.context.annotation.Import;

// 这个也会spring容器托管,注册到容器中,因为他本来就是一个@component
// @Configuration代表这是一个配置类,就和我们之前看的beans.xm1
@Configuration
@Componentscan ("com, kuang.pojo"")
@Import(applicationConfig2.class)
public class applicationConfig {
	//注册一个bean ,就相当于我们之前写的一个bean标签
	//这个方法的名字,就相当于bean标签中的id属性
	//这个方法的返回值,就相当于bean标签中的class属性
	@Bean
	public User user(){
		return new User(); //就是返回要注入到bean的对象!
	}
}

测试类

public class MyTest {
	public static void main(string[] args) {
		//如果完全使用了配置类方式去做,我们就只能通过 Annotationonfig 上下文来获取容器,通过配置类的class对象加载!
		AppicationContext context = new AnnotationConfigApplicationContext(applicationConfig.class);
		User getUser = (User) context.getBean("user");
		System.out.printIn(getuser.getName());
	}
}

10、代理模式

SpringAOP的底层使用了代理模式!
代理模式分类:
静态代理
动态代理

10.1、静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
  • 客户:访问代理对象的人!

代码步骤:
1、接口

//租房
public interface Rent {
	public void rent();
}

2、真实角色

public class Host implements Rent {
	public void rent() {
		System.out.println("房东要出租房子")
	}
}

3、代理角色

public class Proxy implements Rent {
	private Host host;

	public Proxy() {
	}
	public Proxy(Host host) {
		this.host = host
	}
	
	public void rent() {
		seeHouse();
		host.rent();
		hetong();
		fare();
	}

	//看房
	public void seeHouse() {
		System.out.println("中介带人看房");
	}

	//签租赁合同
	public void hetong() {
		System.out.println("签租赁合同");
	}

	//收中介费
	public void fare() {
		System.out.println("收中介费");
	}
}

4、客户端访问代理角色

public class Client {
	public static void main(String[] args) {
		//房东要租房子
		Host host = new Host();
		//代理,中介帮房东租房子,但会有一些附带的操作
		Proxy proxy = new Proxy(host);
		//找中介租房子
		proxy.rent();
	}
}

代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务。
  • 公共就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!

代理模式的缺点:

  • 一个真实的角色就会产生一个代理角色;代码量会翻倍~开发效率降低

10.2、动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的!。
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理。
    • 基于接口 —JDK动态代理
    • 基于类: cglib
    • java字节码实现 :javasist

JDK动态代理需要了解两个类: Proxy:生成动态代理类的类,InvocationHandler:调用处理接口

InvocationHandlerProxy

动态代理类

//等我们会用这个类,自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {
	//被代理的接口
	private Object target;
	
	public void setTarget(Object target) {
		this.target = target;
	}
	
	//生成得到代理类
	/*
	newProxyInstance(ClassLoader loader, 类<?>[] interfaces, InvocationHandler h)
                               throws IllegalArgumentException
	参数: 
	loader - 类加载器来定义代理类 
	interfaces - 代理类实现的接口列表 
	h - 调度方法调用的调用处理函数 
	返回结果: 
	具有由指定的类加载器定义并实现指定接口的代理类的指定调用处理程序的代理实例
    */
	public Object getProxy(){
		return Proxy.newProxyInstance(this.getClass().getClassLoader(),
				target.getClass().getInterfaces(),  this);
	}
	
	//处理代理实例上的方法调用并返回结果,即调用代理对象的方法时附加其他操作的过程
	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 msg) {
		System.out.println("执行了"+msg+"方法");
	}
}

使用动态代理生成代理类

public class Client {
	public static void main(String[] args) {
		//房东要租房子(真实角色)
		Host host = new Host();
		//创建动态代理类		
		ProxyInvocationHandler phi = new ProxyInvocationHandler();
		phi.setTarget(host);//设置要代理的对象
		//使用动态代理类生成代理类,即找一个中介代理房东租房子
		Rent proxy = phi.getProxy();
		//找中介租房子
		proxy.rent();
	}
}

11、AOP

11.1、什么是AOP?

AOP (Aspect Oriented Programming)意为: 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
在这里插入图片描述

11.2 AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等 …
  • 切面(ASPECT): 横切关注点被模块化的特殊对象。即,它是一个类。例如创建日志的类(Log)
  • 通知 (Advice): 切面必须要完成的工作。即,它是类中的一个方法。例如日志类中的日志方法(Log 中的方法)
  • 目标(Target):被通知对象。 (接口或方法)
  • 代理 (Proxy): 向目标对象应用通知之后创建的对象。 (代理类)
  • 切入点 (PointCut): 切面通知执行的“地点”的定义。(执行位置)
  • 连接点 (JointPoint) : 与切入点匹配的执行点。(执行位置)

SpringAOP中,有五种通知类型(Advice):

通知类型连接点实现接口对应注解
前置通知方法前org.springframework.aop.MethodBeforeAdvice@Before
后置通知方法后org.springframework.aop.AfterReturningAdvice@After
环绕通知方法前后org.springframework.aop.MethodInterceptor@Around
异常通知方法抛出异常后org.springframework.aop.ThrowsAdvice@AfterThrowing
返回后通知通知方法在原始切入点方法后运行org.springframework.aop.IntroductionInterceptor@AfterReturning

注意:要正确导入Spring关于aop的包

11.2.1使用Spring的API接口实现

接口及实现类

public interface UserService {
	void add();
	void delete();
}

public class UserServiceImpl implements UserService {
	public void add() {
		System.out.println("增加了一个用户");
	}
	
	public void delete() {
		System.out.println("删除了一个用户");
	}
}

前置通知实例

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
	//method: 要执行的目标对象的方法
	//args:参数
	//target:对象
	public void before(Method method, Object[] args, Object target) {
		System.out.println(target.getClass().getName() + "的"
		+ method.getName() + "要被执行");
	}
}

后置通知实例

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
	//returnValue:目标对象方法执行后返回的结果
	//method: 要执行的目标对象的方法
	//args:参数
	//target:对象
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) {
		System.out.println("执行了"
		+ method.getName() + "返回结果为:" + returnValue);
	}
}

注册bean并配置aop

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop
  https://www.springframework.org/schema/aop/spring-aop.xsd">
  
  <!--注册bean -->
  <bean id="userService" class="com.aop.UserServiceImpl"/>
  <bean id="log" class="com.aop.Log"/>
  <bean id="afterLog" class="com.aop.AfterLog"/>

  <!--方式一:使用Spring原生 API接口-->
  <!--配置aop,需要导入aop的约束-->
  <aop:config>
  		<!--切入点:expression:表达式 , execution(要执行的位置 * * * * *)-->
  		<aop:pointcut id="pointcut" expression="execution(* com.aop.UserServiceImpl.*(..))"/>
  		
  		<!--执行环绕增加-->
  		<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
  		<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
  </aop:config>
</beans>

测试

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		//动态代理的是接口
		UserService userService = (UserService) context.getBean("userService");
		userService.add();
	}
}

11.2.2自定义类实现AOP(切面)

切面类

public class Pointcut() {
	public void before() {
		System.out.println("方法执行前执行");
	}
	public void after() {
		System.out.println("方法执行后执行");
	}
}

注册bean并配置aop

<?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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop
  https://www.springframework.org/schema/aop/spring-aop.xsd">
  
  <!--注册bean -->
  <bean id="userService" class="com.aop.UserServiceImpl"/>
  
  <bean id="mypointcut" class="com.aop.PointCut"/>

  <!--方式二:切面使用-->
  <!--配置aop,需要导入aop的约束-->
  <aop:config>
  		<!--自定义切面,ref 要引入的切面类-->
  		<aop:aspect ref="mypointcut">
  			<!--切入点-->
	  		<aop:pointcut id="pointcut" expression="execution(* com.aop.UserServiceImpl.*(..))"/>
	  		
	  		<!--通知,method切入类的方法-->
	  		<aop:before method="before" pointcut-ref="pointcut"/>
	  		<aop:after method="after" pointcut-ref="pointcut"/>
  		</aop:aspect>
  </aop:config>
</beans>

11.2.3使用注解的方式实现AOP

注解实现切面类

import org.aspectj.lang.annotatin.*;

@Aspect //标注这个类是一个切面
public class Pointcut() {

	@Before("execution(* com.aop.UserServiceImpl.*(..))")
	public void before() {
		System.out.println("方法执行前执行");
	}
	
	@After("execution(* com.aop.UserServiceImpl.*(..))")
	public void after() {
		System.out.println("方法执行后执行");
	}
	
	//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
	@Around("execution(* com.aop.UserServiceImpl.*(..))")
	public void around(ProceedingJionPoint jp) throws Throwable {
		System.out.println("环绕前");
		jp.proceed(); //执行目标方法
		System.out.println("环绕后");
	}
}

注册bean并配置aop

<?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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop
  https://www.springframework.org/schema/aop/spring-aop.xsd">
  
  <!--注册bean -->
  <bean id="userService" class="com.aop.UserServiceImpl"/>
  
  <bean id="mypointcut" class="com.aop.PointCut"/>
  <!--开注解支持! JDK(默认 proxy-target-class="false")  cglib实现 (proxy-target-class="true") -->
  <aop:aspectj-autoproxy/>
</beans>

12、整合Mybatis

1、根据以下条件导入mybatis-spring包
在这里插入图片描述
2、接口及实现类

public interface UserMapper {
  @Select("SELECT * FROM users WHERE id = #{userId}")
  User getUser(@Param("userId") String userId);
}

public class UserMapperImpl implements UserMapper {

  private SqlSession sqlSession;

  public void setSqlSession(SqlSession sqlSession) {
    this.sqlSession = sqlSession;
  }

  public User getUser(String userId) {
  	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    return userMapper.getUser(userId);
  }
}

3、编写spring-mybatis配置文件

<?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
  https://www.springframework.org/schema/beans/spring-beans.xsd">
  
  <!--DataSource:使用Spring的数据源替换Mybatis的配置 c3pe dbcp druid
  我们这里使用Spring提供的JDBC ; org.springframework.jdbc.datasource -->
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
	<property name="url" value ="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEcoding=UTF-8" />
	<property name="username" value="root"/>
	<property name="password" value="123456"/>
  </bean>
  
  <!--管理sqlSessionFactory-->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	  <property name="dataSource" ref="dataSource" />
	  <!--绑定Mybatis配置文件,
	  configLocation:绑定mybatis自己的配置文件,
	  mapperLocations:注册mapper.xml文件-->
	  <property name="configLocation" value="classpath:mybatis-config.xml"/>
	  <property name="mapperLocations" value="classpath:com/mapper/*.xm1"/>
  </bean> 
  
   <!--管理sqlSession,使用SqlSessionTemplate创建sqlSession-->
  <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
	  <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
	  <constructor-arg index="0" ref="sqlSessionFactory" />
  </bean>
  
  <!--注册实现类,并注入sqlSession-->
  <bean id="userMapper" class="com.mapper.UserMapperImpl">
  	<property name="sqlSession" ref="sqlSession" />
  </bean>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值