说明:本文部分内容参考其他优秀博客后结合自己实战例子改编如下

Spring框架是个轻量级的Java EE框架。所谓轻量级,是指不依赖于容器就能运行的。Struts、Hibernate也是轻量级的。

轻量级框架是相对于重量级框架而言的,重量级框架必须依赖特定的容器,例如EJB框架就必须运行在Glassfish、JBoss等支持EJB的容器中,而不能运行在Tomcat中。——《Java Web整合开发 王者归来》

Spring以IoC、AOP为主要思想,其中IoC,Inversion of Control 指控制反转或反向控制。在Spring框架中我们通过配置创建类对象,由Spring在运行阶段实例化、组装对象。

AOP,Aspect Oriented Programming,面向切面编程,其思想是在执行某些代码前执行另外的代码,使程序更灵活、扩展性更好,可以随便地添加、删除某些功能。Servlet中的Filter便是一种AOP思想的实现。

Spring的核心是控制反转(IoC)和面向切面(AOP)简单来说,Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架。

即Spring在JavaEE的三层架构[表现层(Web层)、业务逻辑层(Service层)、数据访问层(DAO层)]中,每一层均提供了不同的解决技术。如下:

• 表现层(Web层):Spring MVC

• 业务逻辑层(Service层):Spring的IoC

• 数据访问层(DAO层):Spring的jdbcTemplate

Spring的优点

  • 方便解耦,简化开发 (高内聚低耦合)

    Spring就是一个大工厂(容器),可以将所有对象创建和依赖关系维护,交给Spring管理

    spring工厂是用于生成bean

  • AOP编程的支持

    Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能

  • 声明式事务的支持

    只需要通过配置就可以完成对事务的管理,而无需手动编程

  • 方便程序的测试

    Spring对Junit4支持,可以通过注解方便的测试Spring程序

  • 方便集成各种优秀框架

    Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支持

  • 降低JavaEE API的使用难度

    Spring 对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低

一、Spring中的IoC操作

 将对象的创建交由Spring框架进行管理。

 IoC操作分为:IoC配置文件方式和IoC的注解方式。

1. IoC入门案例

(1)导入Spring框架中的相关jar包,这里只导入Spring的Core模块(Core模块是框架的核心类库)下的jar包(使用IoC的基本操作,并不需要导入spring-framework-4.2.0的所有jar包,

只导入spring-beansspring-corespring-context、spring-expressionspring-aop这5个jar包),以及 支持日志输出的 commons-logging 和 log4j 的jar包;

(2)创建一个普通的Java类,并在该类中创建方法,如下:

  1. package com.wm103.ioc;
  2.  
  3. /**
  4. * Created by DreamBoy on 2018/3/17.
  5. */
  6. public class User {
  7. public void add() {
  8. System.out.println("User Add Method.");
  9. }
  10.  
  11. @Override
  12. public String toString() {
  13. return "This is a user object.";
  14. }
  15. }

(3)创建Spring的配置文件,进行Bean的配置

Spring的核心配置文件名称和位置不是固定的。但官方件建议将该核心配置文件放在src目录下,且命名为 applicationContext.xml。

这里为了方便,将核心配置文件放在src目录下,并命名为 applicationContext.xml,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- 配置service
  7. <bean> 配置需要创建的对象
  8. id :用于之后从spring容器获得实例时使用的
  9. class :需要创建实例的全限定类名
  10. -->
    <bean id="user" class="com.wm103.ioc.User"></bean>
  11. </beans>

(4)编写测试类进行测试,通过配置文件创建类对象   

  1. package com.wm103.ioc;
  2.  
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6.  
  7. /**
  8. * Created by DreamBoy on 2018/3/17.
  9. */
  10. public class TestIoc {
  11. @Test
  12. public void runUser() {
  13. // 1. 加载Spring配置文件,根据创建对象
  14. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  15. // 2. 得到配置创建的对象
  16. User user = (User) context.getBean("user");
  17. System.out.println(user);
  18. user.add();
  19. }
  20. }

2. Spring的bean管理(配置文件)

Bean实例化的方式

 在Spring中通过配置文件创建对象。

 Bean实例化三种方式实现:

(1)使用类的无参数构造创建,如:

  1. <!-- 等同于 user = new com.wm103.ioc.User(); -->
  2. <bean id="user" class="com.wm103.ioc.User"></bean>

(2)使用静态工厂创建

如果一个Bean不能通过new直接实例化,而是通过工厂类的某个静态方法创建的,需要把<bean>class属性配置为工厂类。如:

  1. <!-- 等同于 user = com.wm103.ioc.UserFactory.createInstance(); -->
  2. <bean id="user" class="com.wm103.ioc.UserFactory" factory-method="createInstance"></bean>

(3)使用实例工厂创建

 如果一个Bean不能通过new直接实例化,而是通过工厂类的某个实例方法创建的,需要先配置工厂的<bean>标签,然后在需要创建的对象的bean标签的factory-bean属性配置为工厂类对象,factory-method属性配置为产生实例的方法。如:

  1. <!-- 等同于 userFactory = new com.wm103.ioc.UserFactory(); -->
  2. <bean id="userFactory" class="com.wm103.ioc.UserFactory"></bean>
  3. <!-- 等同于 user = userFactory.createInstance(); -->
  4. <bean id="user" factory-bean="userFactory" factory-method="createInstance"></bean>

 Bean标签的常用属性

(1)id属性:用于指定配置对象的名称,不能包含特殊符号。 
  (2)class属性:创建对象所在类的全路径。 
  (3)name属性:功能同id属性一致。但是在name属性值中可以包含特殊符号。 
  (4)scope属性

  • singleton:默认值,单例

    单例模式下,在程序下只有一个实例。非单态模式下,每次请求该Bean,都会生成一个新的对象。

  • prototype:多例

  • request:创建对象后将对象存放到request域

  • session:创建对象后将对象存放到session域

  • globalSession:创建对象后将对象存放到globalSession域

3. DI的依赖注入

属性依赖注入

  • 依赖注入方式:手动装配 和 自动装配

  • 手动装配:一般进行配置信息都采用手动

    基于xml装配:构造方法、setter方法

  • 自动装配(基于注解装配):

  属性注入指创建对象时,向类对象的属性设置属性值。

  在Spring框架中支持set方法注入和有参构造函数注入,即创建对象后通过set方法设置属性或采用有参构造函数创建对象并初始化属性。

3.1 使用有参构造函数注入属性

 案例:Student.java 提供有单参的构造方法

  1. package com.wm103.ioc;
  2. public class Student {
  3. private String name;
  4.  
  5. public Student(String name) {
  6. this.name = name;
  7. }
  8.  
  9. @Override
  10. public String toString() {
  11. return "Student{" +
  12. "name='" + name + '\'' +
  13. '}';
  14. }
  15. }

spring bean的配置:

  1. <bean id="student" class="com.wm103.ioc.Student">
  2. <constructor-arg name="name" value="DreamBoy"></constructor-arg>
  3. </bean>

提供有多参的构造方法

  1. public class User {
  2.  
  3. private Integer uid;
  4. private String username;
  5. private Integer age;
  6.  
  7. public User(Integer uid, String username) {
  8. super();
  9. this.uid = uid;
  10. this.username = username;
  11. }
  12.  
  13. public User(String username, Integer age) {
  14. super();
  15. this.username = username;
  16. this.age = age;
  17. }

spring bean的配置:

  1. <!-- 构造方法注入
  2. * <constructor-arg> 用于配置构造方法一个参数argument
  3. name :参数的名称
  4. value:设置普通数据
  5. ref:引用数据,一般是另一个bean id值
  6.  
  7. index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。
  8. type :确定参数类型
  9. 例如:使用名称name
  10. <constructor-arg name="username" value="jack"></constructor-arg>
  11. <constructor-arg name="age" value=""></constructor-arg>
  12. 例如2:【类型type 和 索引 index】
  13. <constructor-arg index="" type="java.lang.String" value=""></constructor-arg>
  14. <constructor-arg index="" type="java.lang.Integer" value=""></constructor-arg>
  15. -->
  16. <bean id="userId" class="com.itheima.f_xml.a_constructor.User" >
  17. <constructor-arg index="" type="java.lang.String" value=""></constructor-arg>
  18. <constructor-arg index="" type="java.lang.Integer" value=""></constructor-arg>
  19. </bean>

创建Student对象进行测试:

  1. @Test
  2. public void runStudent() {
  3. // 1. 加载Spring配置文件,根据创建对象
  4. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  5. // 2. 得到配置创建的对象
  6. Student student = (Student) context.getBean("student");
  7. System.out.println(student);
  8. }

3.2 使用set方法注入属性

案例:Teacher.java 提供属性的set方法

  1. package com.wm103.ioc;
  2. public class Teacher {
  3. private String name;
  4.  
  5. public void setName(String name) {
  6. this.name = name;
  7. }
  8.  
  9. @Override
  10. public String toString() {
  11. return "Teacher{" +
  12. "name='" + name + '\'' +
  13. '}';
  14. }
  15. }

bean的配置:

  1. <bean id="teacher" class="com.wm103.ioc.Teacher">
  2. <property name="name" value="Teacher Wu"></property>
  3. </bean>

创建Teacher对象进行测试:

  1. public void runTeacher() {
  2. // 1. 加载Spring配置文件,根据创建对象
  3. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  4. // 2. 得到配置创建的对象
  5. Teacher teacher = (Teacher) context.getBean("teacher");
  6. System.out.println(teacher);
  7. }

3.3 注入对象类型属性

以三层架构中的service层和dao层为例,为了让service层使用dao层的类创建的对象,需要将dao对象注入到service层类中。具体实现过程中如下:

(1)创建service类、dao层接口、dao类,如下: UserService.java

  1. package com.wm103.exp;
  2. public class UserService {
  3. private UserDao userDao; // 声明为接口类型,降低service层与dao层的耦合度,不依赖于dao层的具体实现
  4.  
  5. public void setUserDao(UserDao userDao) {
  6. this.userDao = userDao;
  7. }
  8.  
  9. public void add() {
  10. System.out.println("UserService Add...");
  11. this.userDao.add();
  12. }
  13. }

UserDao.java

  1. package com.wm103.exp;
  2.  
  3. /**
  4. * 暴露给service层的接口
  5. * Created by DreamBoy on 2018/3/17.
  6. */
  7. public interface UserDao {
  8. void add();
  9. }

UserDaoImpl.java

  1. package com.wm103.exp;
  2.  
  3. /**
  4. * 接口UserDao的具体实现
  5. * Created by DreamBoy on 2018/3/17.
  6. */
  7. public class UserDaoImpl implements UserDao {
  8. @Override
  9. public void add() {
  10. System.out.println("UserDaoImpl Add...");
  11. }
  12. }

(2)在配置文件中注入关系,如下:

  1. <!-- 配置service和dao对象 -->
  2. <!-- 因为service依赖于dao,所以先进行dao对象的bean配置 -->
  3. <bean id="userDaoImpl" class="com.wm103.exp.UserDaoImpl"></bean>
  4. <bean id="userService" class="com.wm103.exp.UserService">
  5. <!--
  6. 注入dao对象
  7. name属性值为:service中的某一属性名称
  8. ref属性值为:被引用的对象对应的bean标签的id属性值
  9. -->
  10. <property name="userDao" ref="userDaoImpl"></property>
  11. </bean>

(3)创建测试方法进行测试,如下:

  1. @Test
  2. public void runUserService() {
  3. // 1. 加载Spring配置文件,根据创建对象
  4. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  5. // 2. 得到配置创建的对象
  6. UserService userService = (UserService) context.getBean("userService");
  7. userService.add();
  8. }

3.4 p名称空间注入属性

之前提到了一种set方法的属性注入方式,这里将介绍另一种属性注入的方式,名为 p名称空间注入。对比set方法的属性注入方式,核心配置文件配置修改如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <bean id="teacher" class="com.wm103.ioc.Teacher" p:name="Teacher Wu"></bean>
  7. </beans>

3.5 注入复杂类型属性

对象注入复杂类型属性,如数组、List、Map、Properties。

案例:PropertyDemo.java

  1. package com.wm103.ioc;
  2.  
  3. import java.util.List;
  4. import java.util.Map;
  5. import java.util.Properties;
  6.  
  7. public class PropertyDemo {
  8. private String[] arrs;
  9. private List<String> list;
  10. private Map<String, String> map;
  11. private Properties properties;
  12.  
  13. public String[] getArrs() {
  14. return arrs;
  15. }
  16.  
  17. public void setArrs(String[] arrs) {
  18. this.arrs = arrs;
  19. }
  20.  
  21. public List<String> getList() {
  22. return list;
  23. }
  24.  
  25. public void setList(List<String> list) {
  26. this.list = list;
  27. }
  28.  
  29. public Map<String, String> getMap() {
  30. return map;
  31. }
  32.  
  33. public void setMap(Map<String, String> map) {
  34. this.map = map;
  35. }
  36.  
  37. public Properties getProperties() {
  38. return properties;
  39. }
  40.  
  41. public void setProperties(Properties properties) {
  42. this.properties = properties;
  43. }
  44. }

bean配置文件,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="prop" class="com.wm103.ioc.PropertyDemo">
  6. <!-- 注入数组 -->
  7. <property name="arrs">
  8. <list>
  9. <value>Value of Array</value>
  10. <value>Value of Array</value>
  11. <value>Value of Array</value>
  12. </list>
  13. </property>
  14. <!-- 注入List集合 -->
  15. <property name="list">
  16. <list>
  17. <value>Value of List</value>
  18. <value>Value of List</value>
  19. <value>Value of List</value>
  20. </list>
  21. </property>
  22. <!-- 注入Map集合 -->
  23. <property name="map">
  24. <map>
  25. <entry key="key1" value="Value 1 of Map"></entry>
  26. <entry key="key2" value="Value 2 of Map"></entry>
  27. <entry key="key3" value="Value 3 of Map"></entry>
  28. </map>
  29. </property>
  30. <!-- 注入Properties -->
  31. <property name="properties">
  32. <props>
  33. <prop key="username">root</prop>
  34. <prop key="password"></prop>
  35. </props>
  36. </property>
  37. </bean>
  38. </beans>

创建PropertyDemo对象进行测试:

  1. @Test
  2. public void runPropertyDemo() {
    // 1. 加载Spring配置文件,根据创建对象
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // 2. 得到配置创建的对象
    PropertyDemo pd = (PropertyDemo) context.getBean("prop");
    System.out.println(pd);
    System.out.println(Arrays.toString(pd.getArrs()));
    System.out.println(pd.getList());
    System.out.println(pd.getMap());
    System.out.println(pd.getProperties());
    }

IoC和DI的区别

  IoC,控制反转,将传统的对象创建流程转变为交由框架进行创建和管理。在Spring中,对象的创建交给Spring进行配置。它包括依赖注入。

 DI,依赖注入,向类的属性设置值。

 IoC与DI的关系:依赖注入不能单独存在,需要在IoC基础之上完成操作。

4. Spring的bean管理(注解)

 注解是代码中特殊的标记,使用注解可以完成特定的功能。注解可以使用在类、方法或属性上,写法如:@注解名称(属性名称=属性值)

Spring的bean管理注解方式,案例如下。

  • 注解:就是一个类,使用@注解名称
  • 开发中:使用注解 取代 xml配置文件。 
    1. @Component取代<bean class=""> 
      @Component("id") 取代 <bean id="" class=""> 
    2. web开发,提供3个@Component注解衍生注解(功能一样)取代 
    @Repository :dao层 
    @Service:service层 
    @Controller:web层 
    3. 依赖注入,给私有字段设值,也可以给setter方法设值
    • 普通值:@Value(" ")
    • 引用值: 
      方式1:按照【类型】注入 
      @Autowired 
      方式2:按照【名称】注入1 
      @Autowired 
      @Qualifier("名称") 
      方式3:按照【名称】注入2 
      @Resource("名称")
       
      4.生命周期 
      初始化:@PostConstruct 
      销毁:@PreDestroy
       
      5.作用域 
      @Scope("prototype") 多例 
      注解使用前提,添加命名空间,让spring扫描含有注解类

4.1 Spring注解开发准备

(1)导入jar包:

  • 导入基本的jar包:commons-logginglog4jspring-beansspring-contextspring-corespring-expression相关jar包。
  • 导入AOP的jar包:spring-aop jar包。

(2)创建类、方法

User.java

  1. package com.wm103.anno;
  2.  
  3. import org.springframework.stereotype.Component;
  4.  
  5. public class User {
  6. public void add() {
  7. System.out.println("User Add Method.");
  8. }
  9. }

(3)创建Spring配置文件,引入约束;并开启注解扫描   

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  1. <!--
  2. 开启注解扫描
  3. ()到包中扫描类、方法、属性上是否有注解
  4. -->
  5. <context:component-scan base-package="com.wm103"></context:component-scan>
  6.  
  7. <!--
  8. ()只扫描属性上的注解
  9. -->
  10. <!--<context:annotation-config></context:annotation-config>-->
  11. </beans>

4.2 注解创建对象

在创建对象的类上面使用注解实现,如:

  1. @Component(value="user")
  2. public class User {

创建测试类 TestAnno.java和测试方法,如:

  1. package com.wm103.anno;
  2.  
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6.  
  7. public class TestAnno {
  8.  
  9. @Test
  10. public void runUser() {
    // 1. 加载Spring配置文件,根据创建对象 
  11. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // 2. 得到配置创建的对象
  12. User user = (User) context.getBean("user");
  13. user.add();
  14. }
  15. }

除了上述提到的 @Component注解外,Spring中还提供了@Component的3个衍生注解,其功能就目前来说是一致的,均是为了创建对象。

  • @Controller :WEB层
  • @Service :业务层
  • @Repository :持久层

    以单例或多实例方式创建对象,默认为单例,多例对象设置注解如下:

  1. @Component(value="user")
  2. @Scope(value="prototype")
  3. public class User {

4.3 注解注入属性

 案例:创建Service类和Dao类,并在Service中注入Dao对象。如下:

(1)创建Dao和Service对象

 UserDao.java

  1. package com.wm103.anno;
  2.  
  3. import org.springframework.stereotype.Repository;
  4.  
  5. @Repository(value="userDao")
  6. public class UserDao {
  7. public void add() {
  8. System.out.println("UserDao Add Method.");
  9. }
  10. }

UserService.java

  1. package com.wm103.anno;
  2.  
  3. import org.springframework.stereotype.Service;
  4.  
  5. import javax.annotation.Resource;
  6.  
  7. @Service(value="userService")
  8. public class UserService {
  9. public void add() {
  10. System.out.println("UserService Add Method.");
  11. userDao.add();
  12. }
  13. }

(2)在Service类中定义UserDao类型的属性,并使用注解完成对象的注入

  @Autowired:自动注入或自动装配,是根据类名去找到类对应的对象来完成注入的。

  1. @Autowired
  2. private UserDao userDao;

或者 @Resource

  1. @Resource(name="userDao")
  2. private UserDao userDao;

其中该注解的name属性值为注解创建Dao对象的value属性的值。

这两种注解方式都不一定要为需要注入的属性定义set方法。

(3)创建测试方法

  1. @Test
  2. public void runUserService() {
    // 1. 加载Spring配置文件,根据创建对象 
  3. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // 2. 得到配置创建的对象
  4. UserService userService = (UserService) context.getBean("userService");
  5. userService.add();
  6. }

注:配置文件和注解混合使用

1)创建对象的操作一般使用配置文件方式实现;

2)注入属性的操作一般使用注解方式实现。

二、Spring框架—面向切面编程(AOP)

1. 什么是AOP

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

  • AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码

  • 经典应用:事务管理、性能监视、安全检查、缓存 、日志等

  • Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码

  • AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入

2. AOP实现原理

  • aop底层将采用代理机制进行实现。

  • 接口 + 实现类 :spring采用 jdk 的动态代理Proxy。

  • 实现类:spring 采用 cglib字节码增强。

3. AOP术语【掌握】

1. target:目标类,需要被代理的类。例如:UserService 
2. Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法 
3. PointCut 切入点:已经被增强的连接点。例如:addUser() 
4. advice 通知/增强,增强代码。例如:after、before 
5. Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程. 
6. proxy 代理类 
7. Aspect(切面): 是切入点pointcut和通知advice的结合 
一个线是一个特殊的面。 
一个切入点和一个通知,组成成一个特殊的面。 

4. AOP实现方式

有四种实现方式:手动方式,半自动方式,全自动方式,注解方式

4.1 手动方式

4.1.1 JDK动态代理

  • JDK动态代理 对“装饰者”设计模式 简化。使用前提:必须有接口

1. 目标类:接口 + 实现类(UserServiceImpl)

  1. public interface UserService {
  2. public void addUser();
  3. public void updateUser();
  4. public void deleteUser();
  5. }

2. 切面类:用于存通知 MyAspect

  1. public class MyAspect {
  2. public void before(){
  3. System.out.println("鸡首");
  4. }
  5. public void after(){
  6. System.out.println("牛后");
  7. }
  8. }

3. 工厂类:编写工厂生成代理

  1. public class MyBeanFactory {
  2.  
  3. public static UserService createService(){
  4. //1 目标类
  5. final UserService userService = new UserServiceImpl();
  6. //2切面类
  7. final MyAspect myAspect = new MyAspect();
  8. /* 3 代理类:将目标类(切入点)和 切面类(通知) 结合 --> 切面
  9. * Proxy.newProxyInstance
  10. * 参数1:loader ,类加载器,动态代理类 运行时创建,任何类都需要类加载器将其加载到内存。
  11. * 一般情况:当前类.class.getClassLoader();
  12. * 目标类实例.getClass().get...
  13. * 参数2:Class[] interfaces 代理类需要实现的所有接口
  14. * 方式1:目标类实例.getClass().getInterfaces() ;注意:只能获得自己接口,不能获得父元素接口
  15. * 方式2:new Class[]{UserService.class}
  16. * 例如:jdbc 驱动 --> DriverManager 获得接口 Connection
  17. * 参数3:InvocationHandler 处理类,接口,必须进行实现类,一般采用匿名内部
  18. * 提供 invoke 方法,代理类的每一个方法执行时,都将调用一次invoke
  19. * 参数31:Object proxy :代理对象
  20. * 参数32:Method method : 代理对象当前执行的方法的描述对象(反射)
  21. * 执行方法名:method.getName()
  22. * 执行方法:method.invoke(对象,实际参数)
  23. * 参数33:Object[] args :方法实际参数
  24. *
  25. */
  26. UserService proxService = (UserService)Proxy.newProxyInstance(
  27. MyBeanFactory.class.getClassLoader(),
  28. userService.getClass().getInterfaces(),
  29. new InvocationHandler() {
  30.  
  31. @Override
  32. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  33.  
  34. //前执行
  35. myAspect.before();
  36.  
  37. //执行目标类的方法
  38. Object obj = method.invoke(userService, args);
  39.  
  40. //后执行
  41. myAspect.after();
  42.  
  43. return obj;
  44. }
  45. });
  46.  
  47. return proxService;
  48. }
  49.  
  50. }

4. 测试

  1. @Test
  2. public void demo01(){
  3. UserService userService = MyBeanFactory.createService();
  4. userService.addUser();
  5. userService.updateUser();
  6. userService.deleteUser();
  7. }

4.1.2 CGLIB字节码增强

  • 没有接口,只有实现类。
  • 采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。

工厂类

  1. public class MyBeanFactory {
  2.  
  3. public static UserServiceImpl createService(){
  4. //1 目标类
  5. final UserServiceImpl userService = new UserServiceImpl();
  6. //2切面类
  7. final MyAspect myAspect = new MyAspect();
  8. // 3.代理类 ,采用cglib,底层创建目标类的子类
  9. //3.1 核心类
  10. Enhancer enhancer = new Enhancer();
  11. //3.2 确定父类
  12. enhancer.setSuperclass(userService.getClass());
  13. /* 3.3 设置回调函数 , MethodInterceptor接口 等效 jdk InvocationHandler接口
  14. * intercept() 等效 jdk invoke()
  15. * 参数1、参数2、参数3:以invoke一样
  16. * 参数4:methodProxy 方法的代理
  17. *
  18. *
  19. */
  20. enhancer.setCallback(new MethodInterceptor(){
  21.  
  22. @Override
  23. public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
  24.  
  25. //前
  26. myAspect.before();
  27.  
  28. //执行目标类的方法
  29. Object obj = method.invoke(userService, args);
  30. // * 执行代理类的父类 ,执行目标类 (目标类和代理类 父子关系)
  31. methodProxy.invokeSuper(proxy, args);
  32.  
  33. //后
  34. myAspect.after();
  35.  
  36. return obj;
  37. }
  38. });
  39. //3.4 创建代理
  40. UserServiceImpl proxService = (UserServiceImpl) enhancer.create();
  41.  
  42. return proxService;
  43. }
  44. }

4.2 半自动

  • 让spring 容器创建代理对象,从spring容器中手动的获取代理对象

4.2.1 目标类

  1. public interface UserService {
  2. public void addUser();
  3. public void updateUser();
  4. public void deleteUser();
  5. }

4.2.2 切面类

  1. package com.spring.aop;
  2.  
  3. import org.aopalliance.intercept.MethodInterceptor;
  4. import org.aopalliance.intercept.MethodInvocation;
  5.  
  6. /**
  7. * 切面类:用于存通知
  8. * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
  9. * 采用“环绕通知” MethodInterceptor
  10. *
  11. */
  12. public class MyAspect implements MethodInterceptor {
  13.  
  14. @Override
  15. public Object invoke(MethodInvocation invocation) throws Throwable {
  16. Object result = null;
  17. try {
  18. System.out.println("--环绕通知开始--开启事务--自动--");
  19. long start = System.currentTimeMillis();
  20.  
  21. //手动执行目标方法(有返回参数 则需返回值)
  22. result = invocation.proceed();
  23.  
  24. long end = System.currentTimeMillis();
  25. System.out.println("总共执行时长" + (end - start) + " 毫秒");
  26.  
  27. System.out.println("--环绕通知结束--提交事务--自动--");
  28. } catch (Throwable t) {
  29. System.out.println("--环绕通知--出现错误");
  30. }
  31. return result;
  32. }
  33. }

4.2.3 Spring 配置

  1. <!-- 创建目标类 -->
  2. <bean id="userServiceId" class="com.spring.aop.UserServiceImpl"></bean>
  3. <bean id="orderServiceId" class="com.spring.aop.OrderService"></bean>
  4. <!-- 创建切面类(通知) -->
  5. <bean id="myAspectId" class="com.spring.aop.MyAspect"></bean>
  6.  
  7. <!-- 创建代理类
  8. * 使用工厂bean FactoryBean ,底层调用 getObject() 返回特殊bean
  9. * ProxyFactoryBean 用于创建代理工厂bean,生成特殊代理对象
  10. interfaces : 确定接口们
  11. 通过<array>可以设置多个值
  12. 只有一个值时,value=""
  13. target : 确定目标类
  14. interceptorNames : 通知 切面类的名称,类型String[],如果设置一个值 value=""
  15. optimize :强制使用cglib
  16. <property name="optimize" value="true"></property>
  17. 底层机制
  18. 如果目标类有接口,采用jdk动态代理
  19. 如果没有接口,采用cglib 字节码增强
  20. 如果声明 optimize = true ,无论是否有接口,都采用cglib
  21. -->
  22. <bean id="proxyServiceId" class="org.springframework.aop.framework.ProxyFactoryBean">
  23. <property name="interfaces" value="com.spring.aop.UserService"></property>
  24. <property name="target" ref="userServiceId"></property>
  25. <property name="interceptorNames" value="myAspectId"></property>
  26. </bean>

4.2.4 测试

  1. @Test
  2. public void demo01(){
  3. // 1. 加载Spring配置文件,根据创建对象 
  4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  5.  
  6. //获得代理类
  7. UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
  8. userService.addUser();
  9. userService.updateUser();
  10. userService.deleteUser();
  11. }

4.3 全自动

  • 从spring 容器获得目标类,如果配置aop,spring将自动生成代理。

4.3.1 切面类

  1. package com.spring.aop;
  2.  
  3. import org.aopalliance.intercept.MethodInterceptor;
  4. import org.aopalliance.intercept.MethodInvocation;
  5.  
  6. /**
  7. * 切面类:用于存通知
  8. * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
  9. * 采用“环绕通知” MethodInterceptor
  10. *
  11. */
  12. public class MyAspectZD implements MethodInterceptor {
  13.  
  14. @Override
  15. public Object invoke(MethodInvocation invocation) throws Throwable {
  16. Object result = null;
  17. try {
  18. System.out.println("--环绕通知开始--开启事务--自动--");
  19. long start = System.currentTimeMillis();
  20.  
  21. //手动执行目标方法(有返回参数 则需返回值)
  22. result = invocation.proceed();
  23.  
  24. long end = System.currentTimeMillis();
  25. System.out.println("总共执行时长" + (end - start) + " 毫秒");
  26.  
  27. System.out.println("--环绕通知结束--提交事务--自动--");
  28. } catch (Throwable t) {
  29. System.out.println("--环绕通知--出现错误");
  30. }
  31. return result;
  32. }
  33. }

切面类中根据获取到的注解来通知,示例如下:

  1. package com.demo.aop;
  2.  
  3. import com.demo.annotation.DataSourceChange;
  4. import com.demo.datasource.DynamicDataSourceHolder;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.aopalliance.intercept.MethodInterceptor;
  7. import org.aopalliance.intercept.MethodInvocation;
  8.  
  9. import java.lang.reflect.Method;
  10.  
  11. @Slf4j
  12. public class DynamicDataSourceAspectDao implements MethodInterceptor {
  13. /**
  14. * 切面类:用于存通知
  15. * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
  16. * 采用“环绕通知” MethodInterceptor
  17. * @param invocation
  18. * @return
  19. * @throws Throwable
  20. */
  21. @Override
  22. public Object invoke(MethodInvocation invocation) throws Throwable {
  23. log.info("around");
  24. Object result = null;
  25. //获取代理接口或者类
  26. Object target = joinPoint.getTarget();
  27. String methodName = joinPoint.getSignature().getName();
  28. //获取目标类的接口,所以注解@DataSourceChange需要写在接口上
  29. //Class<?>[] clazz = target.getClass().getInterfaces();
  30. //获取目标类,所以注解@DataSourceChange需要写在类里面
  31. Class<?>[] clazz = new Class<?>[]{target.getClass()};
  32. Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();
  33. try {
  34. Method method = clazz[].getMethod(methodName, parameterTypes);
  35. //判断是否使用了该注解
  36. if (method != null && method.isAnnotationPresent(DataSourceChange.class)) {
  37. DataSourceChange data = method.getAnnotation(DataSourceChange.class);
  38. if (data.slave()) {
  39. DynamicDataSourceHolder.setDataSource(DynamicDataSourceHolder.DB_SLAVE);
  40. } else {
  41. DynamicDataSourceHolder.setDataSource(DynamicDataSourceHolder.DB_MASTER);
  42. }
  43. }
  44.  
  45. System.out.println("--环绕通知开始--开启事务--自动--");
  46. long start = System.currentTimeMillis();
  47.  
  48. //手动执行目标方法(有返回参数 则需返回值)
  49. result = invocation.proceed();
  50.  
  51. long end = System.currentTimeMillis();
  52. System.out.println("总共执行时长" + (end - start) + " 毫秒");
  53.  
  54. System.out.println("--环绕通知结束--提交事务--自动--");
  55. }
  56. catch (Throwable ex) {
  57. System.out.println("--环绕通知--出现错误");
  58. log.error(String.format("Choose DataSource error, method:%s, msg:%s", methodName, ex.getMessage()));
  59. }
  60. finally {
  61. DynamicDataSourceHolder.clearDataSource();
  62. }
  63. return result;
  64. }
  65. }

4.3.2 Spring 配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/aop
  11. http://www.springframework.org/schema/aop/spring-aop.xsd">
  12. <!-- 创建目标类 -->
  13. <bean id="userServiceId" class="com.spring.aop.UserServiceImpl"></bean>
  14. <bean id="orderServiceId" class="com.spring.aop.OrderService"></bean>
  15. <!-- 创建切面类(通知) -->
  16. <bean id="myAspectId" class="com.spring.aop.MyAspectZD"></bean>
  17.  
  18. <!-- aop编程
  19. 3.1 导入命名空间
  20. 3.2 使用 <aop:config>进行配置
  21. 默认情况下会采用JDK的动态代理实现AOP(只能对实现了接口的类生成代理,而不能针对类)
  22. 如果proxy-target-class="true" 声明时强制使用cglib代理(针对类实现代理)
  23. <aop:pointcut> 切入点 ,从目标对象获得具体方法
  24. <aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
  25. advice-ref 通知引用
  26. pointcut-ref 切入点引用
    order 切面顺序
  27. 3.3 切入点表达式
  28. execution(* com.spring.aop..*.*(..))
  29. 选择方法 返回值任意 包及所有子包 类名任意 方法名任意 参数任意
  30. 例如:匹配所有”set”开头的方法:execution(* set*(..))
  31. -->
  32. <aop:config proxy-target-class="true">
  33. <aop:pointcut id="myPointCut" expression="execution(* com.spring.aop..*.update*(..))" />
  34. <aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut" order="1" />
  35. </aop:config>
  36. </beans>

4.3.3 测试

  1. @Test
  2. public void demo01(){
  3. // 1. 加载Spring配置文件,根据创建对象
  4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  5.  
  6. // 获得目标类
  7. UserService userService = (UserService) applicationContext.getBean("userServiceId");
  8. userService.addUser();
  9. userService.updateUser();
  10. userService.deleteUser();
  11.  
  12. // 获得目标类
  13. OrderService orderService = (OrderService) applicationContext.getBean("orderServiceId");
  14. orderService.addOrder();
  15. orderService.updateOrder();
  16. orderService.deleteOrder();
  17. }

4.4 注解方式

Spring AOP基于注解的“零配置”方式实现

1. 为了在Spring中启动@AspectJ支持,需要在类加载路径下新增两个AspectJ库:aspectjweaver-1.74.jar和aspectjrt-1.74.jar。除此之外,Spring AOP还需要依赖一个aopalliance-1.0.jar包

2. 定义一个类似XmlAopDemoOrder.java这样的切面

  1. package com.spring.aop;
  2.  
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.*;
  5. import org.springframework.stereotype.Component;
  6.  
  7. /*
  8. * 声明一个切面
  9. * 自动注解AOP
  10. */
  11. @Aspect
  12. @Component(value="xmlAopDemoOrder")
  13. public class XmlAopDemoOrder {
  14. // 配置切点 及要传的参数
  15. @Pointcut("execution(* com.spring.aop.OrderService.GetDemoOrder(..)) && args(id)")
  16. public void pointCut(int id)
  17. {
  18.  
  19. }
  20.  
  21. // 配置连接点 方法开始执行前通知
  22. @Before("pointCut(id)")
  23. public void beforeLog(int id) {
  24. System.out.println("开始执行前置通知 日志记录:"+id);
  25. }
  26. // 方法执行完后通知
  27. @After("pointCut(id)")
  28. public void afterLog(int id) {
  29. System.out.println("方法执行完后置通知 日志记录:"+id);
  30. }
  31. // 执行成功后通知
  32. @AfterReturning("pointCut(id)")
  33. public void afterReturningLog(int id) {
  34. System.out.println("方法成功执行后通知 日志记录:"+id);
  35. }
  36. // 抛出异常后通知
  37. @AfterThrowing("pointCut(id)")
  38. public void afterThrowingLog(int id) {
  39. System.out.println("方法抛出异常后通知 日志记录"+id);
  40. }
  41.  
  42. // 环绕通知
  43. @Around("pointCut(id)")
  44. public Object aroundLog(ProceedingJoinPoint joinpoint, int id) {
  45. Object result = null;
  46. try {
  47. System.out.println("环绕通知开始 日志记录"+id);
  48. long start = System.currentTimeMillis();
  49.  
  50. //有返回参数 则需返回值
  51. result = joinpoint.proceed();
  52.  
  53. long end = System.currentTimeMillis();
  54. System.out.println("总共执行时长" + (end - start) + " 毫秒");
  55. System.out.println("环绕通知结束 日志记录"+id);
  56. } catch (Throwable t) {
  57. System.out.println("出现错误");
  58. }
  59. return result;
  60. }
  61. }

3. 定义一个业务组件,如:

  1. package com.spring.aop;
  2.  
  3. import org.springframework.stereotype.Component;
  4.  
  5. /*
  6. * 使用注解创建对象
  7. * @Component取代<bean class="">
  8. * @Component("id") 取代 <bean id="" class="">
  9. */
  10. @Component(value="orderService")
  11. public class OrderService {
  12. public void addOrder()
  13. {
  14. System.out.println("添加订单");
  15. }
  16. public void updateOrder()
  17. {
  18. System.out.println("更新订单");
  19. }
  20. public void deleteOrder()
  21. {
  22. System.out.println("删除订单");
  23. }
  24. public void GetDemoOrder(int id)
  25. {
  26. System.out.println("使用注解获取订单" + id);
  27. }
  28. }

4. 在bean.xml中加入下面配置

  1. <!--
  2. 开启注解扫描
  3. ()到包及其子包下面自动扫描类、方法、属性上是否有注解
  4. -->
  5. <context:component-scan base-package="com.spring.helloworld,com.spring.aop"></context:component-scan>
  6.  
  7. <!--
  8. 启动AspectJ支持,开启自动注解AOP
  9. 使用配置注解,首先我们要将切面在spring上下文中声明成自动代理bean
  10. 默认情况下会采用JDK的动态代理实现AOP(只能对实现了接口的类生成代理,而不能针对类)
  11. 如果proxy-target-class="true" 声明时强制使用cglib代理(针对类实现代理)
  12. -->
  13. <!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->
  14. <aop:aspectj-autoproxy/>

5. 测试

  1. @Test
  2. public void demo01(){
  3. //获得目标类
  4. UserService userService = (UserService) applicationContext.getBean("userServiceId");
  5. userService.addUser();
  6. userService.updateUser();
  7. userService.deleteUser();
  8. //获得目标类
  9. OrderService orderService = (OrderService) applicationContext.getBean("orderServiceId");
  10. orderService.addOrder();
  11. orderService.updateOrder();
  12. orderService.deleteOrder();
  13. //AOP使用注解
  14. orderService.GetDemoOrder();
  15. }

本人推荐使用注解方式实现AOP或者全自动方式

Spring框架IOC和AOP介绍的更多相关文章

  1. Spring框架-IOC和AOP简单总结

    参考博客: https://blog.csdn.net/qq_22583741/article/details/79589910 1.Spring框架是什么,为什么,怎么用 1.1 Spring框架是 ...

  2. Spring框架IOC和AOP的实现原理(概念)

    IoC(Inversion of Control) (1). IoC(Inversion of Control)是指容器控制程序对象之间的关系,而不是传统实现中,由程序代码直接操控.控制权由应用代码中 ...

  3. Spring框架IOC和AOP的实现原理

    IoC(Inversion of Control) (1). IoC(Inversion of Control)是指容器控制程序对象之间的关系,而不是传统实现中,由程序代码直接操控.控制权由应用代码中 ...

  4. Spring框架-IOC和AOP

    IOC:它并不是一种技术实现,而是一种设计思想.在任何一个有实际开发意义的程序项目中,我们会使用很多类来描述它们特有的功能,并且通过类与类之间的相互协作来完成特定的业务逻辑.这个时候,每个类都需要负责 ...

  5. Spring框架IOC容器和AOP解析 非常 有用

    Spring框架IOC容器和AOP解析   主要分析点: 一.Spring开源框架的简介  二.Spring下IOC容器和DI(依赖注入Dependency injection) 三.Spring下面 ...

  6. 自己动手写Spring框架--IOC、MVC

    对于一名Java开发人员,我相信没有人不知道 Spring 框架,而且也能够轻松就说出 Spring 的特性-- IOC.MVC.AOP.ORM(batis). 下面我想简单介绍一下我写的轻量级的 S ...

  7. Spring框架入门之AOP

    Spring框架入门之AOP 一.Spring AOP简单介绍 AOP AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented ...

  8. 简单理解Spring之IOC和AOP及代码示例

    Spring是一个开源框架,主要实现两件事,IOC(控制反转)和AOP(面向切面编程). IOC 控制反转,也可以称为依赖倒置. 所谓依赖,从程序的角度看,就是比如A要调用B的方法,那么A就依赖于B, ...

  9. Spring的IOC和AOP之深剖

    今天,既然讲到了Spring 的IOC和AOP,我们就必须要知道 Spring主要是两件事: 1.开发Bean:2.配置Bean.对于Spring框架来说,它要做的,就是根据配置文件来创建bean实例 ...

随机推荐

  1. win10 UWP 动画

    原文:win10 UWP 动画 本文告诉大家如何写同一个简单的动画. 动画入门 本文开始写一个简单的动画,只是移动矩形作为本文的例子. 在 UWP 移动元素的动画,可以使用 RenderTransfo ...

  2. 51 Nod 1700 首尾排序法

    1700 首尾排序法 有一个长度为n的数组 p1, p2, p3, ⋯, pnp1, p2, p3, ⋯, pn ,里面只包含1到n的整数,且每个数字都不一样.现在要对这个数组进行从小到大排序,排序的 ...

  3. bzoj 1996

    区间 dp $f[i][j][1/0]$ 表示将理想数列的 $[i,j]$ 区间排好的方案数 $f[i][j][1]$ 表示最后进去的是第 $i$ 个人 $f[i][j][0]$ 表示最后进去的是第 ...

  4. 【线性代数】6-5:正定矩阵(Positive Definite Matrices)

    title: [线性代数]6-5:正定矩阵(Positive Definite Matrices) categories: Mathematic Linear Algebra keywords: Po ...

  5. C语言学习笔记9-指针

    1.指针基础 NULL为预处理器变量,是从C继承下来的,该变量在cstdlib头文件中定义 2.指针函数与函数指针 3.指针数组与数组指针 4.

  6. MySQL数据分析(7)-试着使用SQL

    (一) 1.1 启动服务器 Windows版命令: net start mysql 或者 C:\mysql-5.5.20-winx64\mysql-5.5.20-winx64\mysql Mac版命令 ...

  7. redis之不重启,切换RDB备份到AOF备份

    确保redis版本在2.2以上 [root@pyyuc /data 22:23:30]#redis-server -v Redis server v=4.0.10 sha=00000000:0 mal ...

  8. wordpress爆破脚本的编写

    import requests import sys import queue import threading import time import getopt urll='' users='' ...

  9. 解决Android Studio 打开Flutter 项目,找不到设备的问题

    开始设置了ANDROID_HOME环境变量后,发现Flutter 识别不了安卓SDK, 使用命令配置发现配置是失败的,貌似是不支持路径里有空格 复制一份SDK到没有空格的路径后,SDK就能识别了,并且 ...

  10. KVM——以桥接的方式搭建虚拟机网络配置

    以桥接的方式搭建虚拟机网络,其优势是可以将网络中的虚拟机看作是与主机同等地位的服务器. 在原本的局域网中有两台主机,一台是win7(IP: 192.168.0.236),一台是CentOS7(IP: ...