拿捏Java:Spring5

15 阅读17分钟

一、Spring

官网 : spring.io/ 官方下载地址 : repo.spring.io/libs-releas… GitHub : github.com/spring-proj… spring官方文档在这个链接docs.spring.io/spring/docs…

maven:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>6.1.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>6.1.3</version>
</dependency>

1、Spring是一个开源免费的框架 , 容器  .

2、Spring是一个轻量级的框架 , 非侵入式的 .

3、控制反转 IoC  , 面向切面 Aop**

4、对事物的支持 , 对框架的支持

Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器(框架)。

image.png

Spring Boot与Spring Cloud

  • Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务;
  • Spring Cloud是基于Spring Boot实现的;
  • Spring Boot专注于快速、方便集成的单个微服务个体,Spring Cloud关注全局的服务治理框架;
  • Spring Boot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot来实现,Spring Boot可以离开Spring Cloud独立使用开发项目,但是Spring Cloud离不开Spring Boot,属于依赖的关系。
  • SpringBoot在SpringClound中起到了承上启下的作用,如果你要学习SpringCloud必须要学习SpringBoot。

二、IOC理论推导

1、UserDao 接口

2、UserDaoImpl 接口实现类
3、UserService 业务接口
4、UserServiceImpl 业务实现类——业务层调Dao层

用户实际调用的是Service层,Dao层他们不用接触

之前的业务实现需要去service实现类里面修改对应的实现 . 假设我们的这种需求非常大 , 这种方式就根本不适用了, 甚至反人类对吧 , 每次变动 , 都需要修改大量代码 . 这种设计的耦合性太高了, 牵一发而动全身

解决方法: 我们可以在需要用到他的地方 , 不去实现它 , 而是留出一个接口 , 利用set , 我们去代码里修改下

public class UserServiceImpl implements UserService {
   private UserDao userDao;
// 利用set动态实现值的注入
   public void setUserDao(UserDao userDao) {
       this.userDao = userDao;
  }

   @Override
   public void getUser() {
       userDao.getUser();
  }
}

由我们自行控制创建对象 , 把主动权交给了调用者 . 程序不用去管怎么创建,怎么实现了 . 它只负责提供一个接口 .

这种思想 , 从本质上解决了问题 , 我们程序员不再去管理对象的创建了 , 更多的去关注业务的实现 . 耦合性大大降低 . 这也就是IOC的原型 !

三、IOC本质

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

69904013b87ce78e4e20166276138b71.png

IOC是Spring框架的核心内容,使用多种方式完美的实现了IOC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IOC。

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从IOC容器中取出需要的对象。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

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

四、HelloSpring

1、编写一个Hello实体类

public class Hello {
   private String name;

   public String getName() {
       return name;
  }
   public void setName(String name) {
       this.name = name;
  }

   public void show(){
       System.out.println("Hello,"+ name );
  }
}

2、编写我们的spring文件 , 这里我们命名为beans.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就是java对象 , 由Spring创建和管理-->
   <bean id="hello" class="com.kuang.pojo.Hello">
       <property name="name" value="Spring"/>
   </bean>

</beans>

3、我们可以去进行测试了 .

@Test
public void test(){
   //解析beans.xml文件 , 生成管理相应的Bean对象
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //getBean : 参数即为spring配置文件中bean的id .
   Hello hello = (Hello) context.getBean("hello");
   hello.show();
}
  • Hello 对象是谁创建的 ?  hello 对象是由Spring创建的
  • Hello 对象的属性是怎么设置的 ?  hello 对象的属性是由Spring容器设置的

控制反转 :

  • 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的
  • 反转 : 程序本身不创建对象 , 而变成被动的接收对象
  • 依赖注入 : 就是利用set方法来进行注入的.
  • IOC是一种编程思想,由主动的编程变成被动的接收
  • 要想实现不同的操作,可以更改xml中的配置

beans.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">

    <!--使用Spring创建对象,这在Spring中叫bean-->
   <bean id="MysqlImpl" class="com.kuang.dao.impl.UserDaoMySqlImpl"/>
   <bean id="OracleImpl" class="com.kuang.dao.impl.UserDaoOracleImpl"/>
    <!--使用spring中已有的bean-->
   <bean id="ServiceImpl" class="com.kuang.service.impl.UserServiceImpl">
       <!--注意: 这里的name并不是属性 , 而是set方法后面的那部分 , 首字母小写-->
       <!--引用另外一个bean , 不是用value 而是用 ref-->
       <property name="userDao" ref="OracleImpl"/>
   </bean>

</beans>

五、IOC创建对象的方式

  • 通过无参构造方法来创建
<?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="user" class="com.kuang.pojo.User">
       <property name="name" value="kuangshen"/>
   </bean>

</beans>
  • 通过有参构造方法来创建
<!-- 第一种根据index参数下标设置 -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <!-- index指构造方法 , 下标从0开始 -->
   <constructor-arg index="0" value="kuangshen2"/>
</bean>

<!-- 第二种根据参数名字设置 -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <!-- name指参数名 -->
   <constructor-arg name="name" value="kuangshen2"/>
</bean>

<!-- 第三种根据参数类型设置 -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <constructor-arg type="java.lang.String" value="kuangshen2"/>
</bean>

六、Spring 配置

1、别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>

2、bean的配置

<!--bean就是java对象,由Spring创建和管理-->

<!--
   id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
   如果配置id,又配置了name,那么name是别名
   name可以设置多个别名,可以用逗号,分号,空格隔开
   如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;

class是bean的全限定名=包名+类名
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.kuang.pojo.Hello">
   <property name="name" value="Spring"/>
</bean>

3、import

团队的合作通过import来实现 .

<import resource="{path}/beans.xml"/>

七、依赖注入(DI)

1、构造器注入

前面案例

2、set注入(重要)

依赖注入:set注入

  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象的属性由容器注入
<bean id="address" class="com.sweet.pojo.Address">
    <property name="address" value="shanghaimartimeuniversity"></property>
</bean>
    <bean id="student" class="com.sweet.pojo.Student">
    //常量注入
        <property name="name" value="tiantian"></property>
    //bean注入
        <property name="address" ref="address"></property>
    //数组注入
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>三国演义</value>
                <value>水浒传</value>
            </array>
        </property>
   //list注入
        <property name="hobbys">
            <list>
                <value>看电视</value>
                <value>刷抖音</value>
            </list>
        </property>
    //map注入
        <property name="card">
            <map>
                <entry key="1" value="111"></entry>
                <entry key="2" value="222"></entry>
                <entry key="3" value="333"></entry>
            </map>
        </property>
    //set注入
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
            </set>
        </property>
    //null注入
        <property name="wife">
            <null/>
        </property>
   //property注入
        <property name="info">
            <props>
                <prop key="driver">jdbc:localhost:8080</prop>
                <prop key="url">lianjie</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
</bean>

3、其他方式注入-c命名和p命名空间注入

1、P命名空间注入 : 需要在头文件中加入约束文件(必须要有无参构造器)

 导入约束 : xmlns:p="http://www.springframework.org/schema/p"
 
 <!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
 <bean id="user" class="com.kuang.pojo.User" p:name="狂神" p:age="18"/>

2、c 命名空间注入 : 需要在头文件中加入约束文件(必须要有有参构造器)

c 就是所谓的构造器注入!

 导入约束 : xmlns:c="http://www.springframework.org/schema/c"
 <!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
 <bean id="user" class="com.kuang.pojo.User" c:name="狂神" c:age="18"/>

八、Bean作用域

Singleton 单例

当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例

<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">

Prototype 原型

每次从容器中get的时候,都会产生一个新的对象

当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例

<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/> 

image.png

九、Bean自动装配

  • 自动装配是使用spring满足bean依赖的一种方法
  • spring会在应用上下文中为某个bean寻找其依赖的bean

Spring中bean有三种装配机制,分别是:

  1. 在xml中显式配置;
  2. 在java中显式配置;
  3. 隐式的bean发现机制和自动装配

Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
  2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

组件扫描和自动装配组合发挥巨大威力,使得显示的配置降低到最少。

推荐不使用自动装配xml配置 , 而使用注解 .

byName

<bean id="user" class="com.kuang.pojo.User" autowire="byName">
   <property name="str" value="qinjiang"/>
</bean>
  1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
  2. 去spring容器中寻找是否有此字符串名称id的对象。
  3. 如果有,就取出注入;如果没有,就报空指针异常。

byType

在容器上下文中找和自己属性类型一致的bean!

同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。 例如:

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>

<bean id="user" class="com.kuang.pojo.User" autowire="byType">
   <property name="str" value="qinjiang"/>
</bean>

注解实现自动装配

1、在spring配置文件中引入context文件头

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd

完整版:


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

2、开启属性注解支持!

 <context:annotation-config/>

3、测试: `将User类中的set方法去掉,使用@Autowired注解

public class User {
   @Autowired
   private Cat cat;
   @Autowired
   private Dog dog;
   private String str;

   public Cat getCat() {
       return cat;
  }
   public Dog getDog() {
       return dog;
  }
   public String getStr() {
       return str;
  }
}

配置文件中的内容:

<context:annotation-config/>

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User"/>

@Autowired(required=false)  说明:false,对象可以为null;true,对象必须存对象,不能为null。

  • @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
  • @Qualifier不能单独使用。

测试:

1、配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!

<bean id="dog1" class="com.kuang.pojo.Dog"/>
<bean id="dog2" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>

2、没有加Qualifier测试,直接报错

3、在属性上添加Qualifier注解

@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

@Resource

  • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
  • 其次再进行默认的byName方式进行装配;
  • 如果以上都不成功,则按byType的方式自动装配。
  • 都不成功,则报异常。
public class User {
   //如果允许对象为null,设置required = false,默认为true
   @Resource(name = "cat2")
   private Cat cat;
   @Resource
   private Dog dog;
   private String str;
}

@Autowired与@Resource异同:

1、@Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。

2、@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用

3、@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

4、它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。

十、使用注解开发

@Component-设置组件

<!--指定扫描的包,这个包下的注解会生效-->
<context:component-scan base-package="com.sweet.pojo"></context:component-scan>
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
    public String name="sweet";
}
public class MyTest {
    @Test
    public void testMethodAutowire() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean("user", User.class);//id默认为类的小写
        System.out.println(user.name);
    }
}

@Value-设置属性值

@Component
public class User {
    @Value("sweet")
    public String name;
}

衍生注解

@Component三个衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,功能一样,都是将类注册到spring中,装配bean!

  • @Controller:web层
  • @Service:service层
  • @Repository:dao层

写上这些注解,就相当于将这个类交给Spring管理装配了!

作用域

@scope

  • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
  • prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Controller("user")
@Scope("prototype")
public class User {
   @Value("秦疆")
   public String name;
}

小结

XML与注解比较

  • XML可以适用任何场景 ,结构清晰,维护方便
  • 注解不是自己提供的类使用不了,开发简单方便

xml与注解整合开发 :推荐最佳实践

  • xml管理Bean
  • 注解完成属性注入
  • 使用过程中, 可以不用扫描,扫描是为了类上的注解

十一、使用JavaConfig实现配置

JavaConfig 原来是 Spring 的一个子项目,它通过 Java 类的方式提供 Bean 的定义信息,在 Spring4 的版本, JavaConfig 已正式成为 Spring4 的核心功能 。

不使用xml配置文件

1、编写一个实体类,Dog

@Component  //将这个类标注为Spring的一个组件,放到容器中!
public class Dog {
   public String name = "dog";
}

2、新建一个config配置包,编写一个MyConfig配置类

@Configuration  //代表这是一个配置类,相当于之前的bean.xml,这个也会被spring容器托管,因为本来就是一个@Component,就可以用@Component的所有注解
public class MyConfig {

   @Bean //通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
   public Dog dog(){
       return new Dog();//返回要注入到bean的对象
  }

}

3、测试

@Test
public void test2(){
   ApplicationContext applicationContext =
           new AnnotationConfigApplicationContext(MyConfig.class);
   Dog dog = (Dog) applicationContext.getBean("dog");
   System.out.println(dog.name);
}

导入合并其他配置类

@Configuration
@Import(MyConfig2.class)  //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class MyConfig {

   @Bean
   public Dog dog(){
       return new Dog();
  }

}

十二、代理模式——SpringAOP的底层

  • 静态代理
  • 动态代理

image.png

静态代理(代理继承一个接口,组合一个实现类)

角色分析

  • 抽象角色 : 一般使用接口或者抽象类来实现(租房)
  • 真实角色 : 被代理的角色(房东)
  • 代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 (代理,代理调用房东的方法).
  • 客户  :  使用代理角色来进行一些操作 .(租户)
代码实现:
//抽象角色:租房
public interface Rent {
   public void rent();
}

//真实角色: 房东,房东要出租房子
public class Host implements Rent{
   public void rent() {
       System.out.println("房屋出租");
  }
}

//代理角色:中介
public class Proxy implements Rent {

   private Host host;
   public Proxy() { }
   public Proxy(Host host) {
       this.host = host;
  }

   //租房
   public void rent(){
       seeHouse();
       host.rent();
       fare();
  }
   //看房
   public void seeHouse(){
       System.out.println("带房客看房");
  }
   //收中介费
   public void fare(){
       System.out.println("收中介费");
  }
}

/客户类,一般客户都会去找代理!
public class Client {
   public static void main(String[] args) {
       //房东要租房
       Host host = new Host();
       //中介帮助房东
       Proxy proxy = new Proxy(host);

       //你去找中介!
       proxy.rent();
  }
}

静态代理的好处:

  • 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情
  • 公共的业务由代理来完成 . 实现了业务的分工
  • 公共业务发生扩展时变得更加集中和方便

缺点 :

  • 一个真实角色对应一个代理角色,类多了 , 多了代理类 , 工作量变大了 . 开发效率降低

我们在不改变原来的代码的情况下,实现了对原有功能的增强,这是AOP中最核心的思想

image.png

动态代理

  • 动态代理的角色和静态代理的一样 .
  • 动态代理的代理类是动态生成的 . 静态代理的代理类是我们提前写好的
  • 动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理
    • 基于接口的动态代理----JDK动态代理
    • 基于类的动态代理--cglib
    • 现在用的比较多的是 javasist 来生成动态代理 . 百度一下javasist
    • 我们这里使用JDK的原生代码来实现,其余的道理都是一样的!
//使用这个类可以自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private home home;
    public void setHome(home home) {
        this.home = home;
    }

    //生成得到代理类->参数的意义:
    (类加载器,获取要代理的抽象角色,InvocationHandler)
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),home.getClass().getInterfaces(),this);

    }
    
    //处理代理实例,并返回结果  
    (proxy:要代理谁;method:要实现的方法或者接口;args:方法中要传递的参数)
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //利用反射获取代理中的方法,动态代理的本质就是反射机制
        lookhome();
        Object result = method.invoke(home, args);
        fare();
        return result;
    }
    public void lookhome(){
        System.out.println("kanfanfzi");
    }
    public void fare(){
        System.out.println("shouqian");
    }

测试:

public class client {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理角色
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //通过调用程序处理角色处理我们要代理的接口对象,设置要代理的对象
        pih.setHome(host);
        home proxy =(home) pih.getProxy();//proxy是动态生成的,我们并没有写
        proxy.rent();

    }
}

把自动生成代理类的代码统一成一个模板:

public class ProxyInvocationHandler implements InvocationHandler {
    private Object object;
    public void setObject(Object object) {
        this.object = object;
    }
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                object.getClass().getInterfaces(),
                this);
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());//利用反射获得方法的名字
        Object result = method.invoke(object, args);
        return result;
    }
    public void log(String msg){
        System.out.println("zhixing llll "+msg);
    }
}

测试:

public class client {
    public static void main(String[] args) {
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        UserServiceImpl userService = new UserServiceImpl();//真实对象
        pih.setObject(userService);//设置要代理的对象
        UserService proxy = (UserService)pih.getProxy();//自动生成代理
        proxy.add();
        proxy.query();
    }
}

核心:一个动态代理 , 一般代理某一类业务 , 一个动态代理可以代理多个类,代理的是接口!

十三、AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

image.png

Aop在Spring中的作用

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

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

AOP在不改变原有代码的基础上,增加新的功能

image.png

image.png

方式一:Spring-API接口

业务代码:

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}
public class UserServiceImpl implements UserService{
    public void add() { System.out.println("增加了一个用户"); }
    public void delete() { System.out.println("shan了一个用户"); }
    public void update() { System.out.println("gengxin了一个用户"); }
    public void query() { System.out.println("chaxun了一个用户"); }
}

想增加的需求通过Spring AOP实现

public class Log implements MethodBeforeAdvice {
    //method:要执行的目标对象的方法
    //args:要调用方法的参数
    //target:目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
public class AfterLog implements AfterReturningAdvice {
    //returnValue 返回值
    //method被调用的方法
    //args 被调用的方法的对象的参数
    //target 被调用的目标对象
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"
                +method.getName()+"被执行了,返回了"
                +returnValue);
    }
}

配置文件:applicationContext.xml

<!--注册bean-->
<bean id="userService" class="com.sweet.service.UserServiceImpl"/>
<bean id="log" class="com.sweet.log.Log"/>
<bean id="afterLog" class="com.sweet.log.AfterLog"/>
<!--方式一:使用Spring-API接口-->
<!--aop配置-->
<aop:config>
    <!--切入点,expression="execution(执行的位置,修饰词,返回值,类名,方法名,参数名)"-->
    <!--com.sweet.service.UserServiceImpl.*(..))表示把这个类下的所有方法都切入-->
    <aop:pointcut id="pointcut" expression="execution(* com.sweet.service.UserServiceImpl.*(..))"/>
    <!--把log这个类切入到pointcut这个切入点指定的地方-->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"></aop:advisor>
</aop:config>

测试类

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

方式二:自定义类实现AOP,主要是自定义切面

自定义切面类

//自定义的一个切入类
public class DiyPointcut {
    public void before(){
        System.out.println("---------方法执行前---------");
    }
    public void after(){
        System.out.println("---------方法执行后---------");
    }
}

配置文件:applicationContext.xml

<bean id="diy" class="com.sweet.diy.DiyPointcut"></bean>
<aop:config>
    <!--自定义切面,ref表示要引用的类-->
    <aop:aspect ref="diy">
        <!--切入点-->
        <aop:pointcut id="pointcut" expression="execution(* com.sweet.service.UserServiceImpl.*(..))"/>
        <!--通知-->
        <!--在切入点之前插入-->
        <aop:before method="before" pointcut-ref="pointcut"/>
        <!--在切入点之后插入-->
        <aop:after method="after" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>

测试类:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = Context.getBean("userService", UserService.class);
        userService.add();
    }
}

方式三:注解实现AOP

自定义切面类(有注解)

@Aspect
public class AnnotationPointcut {
    @Before("execution(* com.sweet.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("---------方法执行前---------");
    }
    @After("execution(* com.sweet.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("---------方法执行后---------");
    }
}

配置:

<bean id="annocationPointcut" class="com.sweet.diy.AnnotationPointcut"/>
    <!--开启注解模式-->
    <aop:aspectj-autoproxy/>

测试:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = Context.getBean("userService", UserService.class);
        userService.add();
    }
}

十四、整合Mybatis

1、导入jar包

junit、mybatis、mysql-connector-java、spring相关(spring-webmvc、spring-jdbc)、aspectJ AOP 织入器、mybatis-spring整合包 配置Maven静态资源过滤问题!

2、编写配置文件
3、代码实现

Mybatis-Spring