• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

hemkyy7

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

Spring学习-04

1、Spring

1.1、简介

  • 解决企业应用开发的复杂性
  • 理念:使现有的技术更加容易使用
  • 官网:https://spring.io/projects/spring-framework#learn
  • 下载地址:https://repo.spring.io/ui/native/release/org/springframework/spring
  • GitHub: https://github.com/spring-projects
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.16</version>
        </dependency>

1.2、优点

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

== Spring就是一个轻量级的控制反转和面向切面编程的框架

1.3、组成

1.4、扩展

  • SpringBoot:
    • 一个快速开发的脚手架
    • 基于SpringBoot可以快速开发单个微服务
    • 约定大于配置
  • SpringCloud:
    • 是基于SpringBoot实现的

弊端:配置十分繁琐

2、IOC(控制反转)

从用户掌握主动权到程序员掌握主动权,程序的调用。(最初的就是客户点单你要根据他的需求去买菜,可能你之前买的菜用不上了。后来就是用户根据你提供的菜单点餐,客户点的菜都是店里有的。)

  • 控制反转就是:获得的依赖对象反转了
  • 控制反转是一种通过描述(xml或注解)并通过第三方去生产或获取特定对象的方式。在spring中实现控制反转的是ioc容器,其实现的方法是依赖注入(DI)

控制:传统应用程序的对象是由程序本身控制创建的,使用Spring后是由Spring创建的。

反转:程序本身不创建对象,而变成被动的接收对象

依赖注入:利用set方法来进行注入

ioc就是一种编程思想,由主动的编程变成被动的接收

要实现不同的操作只需要在xml配置文件中进行修改。

对象由Spring来创建、管理、装配

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">
    <!--使用Spring来创建对象,在spring中这些都称为bean
         类型  变量名 = new 类型();
        Hello   hello = new Hello();

        bean=对象
        id=变量名
        class = new的对象
        property 相当于给对象中的属性设置一个值
    -->
<bean id="mysqlImpl" class="com.he.dao.UserDaoMysqlImpl"/>
<bean id="oracleImpl" class="com.he.dao.UserDaoOracleImpl"/>
<bean id="UserServiceImpl" class="he.yan.service.UserServiceImpl">
    <!--ref:使用spring容器中创建好的对象
        value:具体对象的值,基本数据类型
    -->
    <property name="userDao" ref="oracleImpl"/>
</bean>

</beans>

此时对象是oracleImpl输出的也是它的内容

实体类:
    
public class UserDaoOracleImpl implements UserDao{
    public void getUser() {
        System.out.println("oracle获取用户数据");
    }
}

测试文件:
    
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class mytest {
    public static void main(String[] args) {
        //用户实际调用的是业务层
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImpl userServiceImpl = (UserServiceImpl)context.getBean("UserServiceImpl");
        userServiceImpl.getUser();
    }
}

结果输出:   oracle获取用户数据

2.2 IOC 创建对象的方式

1.使用无参构造创建对象,默认的
实体类:
public class User {
private  String name;

    public User() {
        System.out.println("这是无参构造");
    }

    public String getName() {
        return name;
    }

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

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

beans.xml
    <bean id="user" class="com.he.pojo.User">
        <property name="name" value="xixi"/>
    </bean>
测试类
public class myTest {
    public static void main(String[] args) {
        ApplicationContext context = new      ClassPathXmlApplicationContext("beans.xml");
        //在执行getBean的时候,user已经创建好了
       User user = (User) context.getBean("user");
        //调用对象方法
       user.show();
    }
}

在调用show方法之前,User对象已经通过无参构造初始化了

2.使用有参构造创建对象
User实体类

public class User {
private  String name;

    public User(String name) {
        this.name = name;
        System.out.println("这是有参构造!");
    }


    public String getName() {
        return name;
    }

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

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

   <!--1.通过下标赋值-->
    <bean id="user" class="com.he.pojo.User">
        <constructor-arg index="0" value="haha"/>
    </bean>
   <!--2.通过参数类型创建,不建议使用。(因为如果有两个string类型就没办法用了)-->
    <bean id="user" class="com.he.pojo.User">
        <constructor-arg type="java.lang.String" value="hehe"/>
    </bean>

    <!--3.通过参数名来设计-->
    <bean id="user" class="com.he.pojo.User">
        <constructor-arg name="name" value="youyou"/>
    </bean>

在配置文件加载的时候,容器中管理的对象已经初始化了

3. Spring的配置

3.1 别名

如果添加了别名
<alias name="user" alias="324wev"></alias>
public class myTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       User user = (User) context.getBean("324wev");
       user.show();
    }
}

3.2 Bean的配置

    <!--
        id: bean的唯一标识符,相当于对象名
        class:bean对象所对应的全限定名-》包名+类型
        name:也是别名,而且可以同时取多个别名(例子中的U2、uf)
    -->
    <bean id="userS" class="com.he.pojo.User2" name="user22 U2 uf" >
        <property name="name" value="2222"/>
    </bean>
测试类中
     User user = (User) context.getBean("uf");

3.3 import

一般用于团队开发,将多个配置文件,导入合并为一个

  • 丽丽 ---->beans.xml
  • 李海 ---->beans2.xml
  • 九九 ---->beans3.xml
  • 总项目 ---->applicationContext.xml
在applicationContext.xml文件中用import标签将三人的配置文件合并
	<import resource="beans.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
  测试类中使用总项目配置
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

4.依赖注入(DI)

4.1 构造器注入

前面说过了

4.2 Set方式注入【重点】

  • 依赖注入:set注入

    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入
4.2.1 注入
实体类文件:
public class Student {
    private  String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;
    private String isAdult;
    private Properties info;
}

public class Address {
    private String address;
}

//ps:自行添加getter、setter、toString()方法。
xml文件:
	<bean id="adr" class="com.he.pojo.Address">
        <property name="address" value="北京"/>
    </bean>

    <bean id="student" class="com.he.pojo.Student">
        <!--1.普通值注入-->
        <property name="name" value="小会"/>
        <!--2.Bean注入-->
        <property name="address" ref="adr"/>
        <!--3.数组注入-->
        <property name="books">
            <array>
                <value>《java基础入门》</value>
                <value>《c语言程序设计》</value>
                <value>《Spring》</value>
            </array>
        </property>
        <!--4.list注入-->
        <property name="hobbies">
            <list>
                <value>阅读</value>
                <value>编程</value>
                <value>跑步</value>
            </list>
        </property>
        <!--5.Map注入-->
        <property name="card">
            <map>
                <entry key="中国建设银行" value="621783295923"/>
                <entry key="中国工商银行" value="621365646544"/>
            </map>
        </property>
        <!--6.set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>BOB</value>
            </set>
        </property>
        <!--7.NULL注入-->
        <property name="isAdult"><null/></property>
        <!--8.Properties注入-->
        <property name="info">
            <props>
                <prop key="学号">20180407234</prop>
                <prop key="专业">应用数学</prop>
                <prop key="姓名">小会</prop>
            </props>
        </property>
    </bean>
4.2.2 测试和结果
测试:
public class myTest {
    public static void main(String[] args) {
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());

    }
}

结果:
Student{name='小会', address=Address{address='北京'}, 
books=[《java基础入门》, 《c语言程序设计》, 《Spring》], 
hobbies=[阅读, 编程, 跑步], 
card={中国建设银行=621365646544, 中国工商银行=621365646544}, 
games=[LOL, BOB], 
isAdult='null', 
info={学号=20180407234, 专业=应用数学, 姓名=小会}}

4.3 拓展方式注入

4.3.1 P命名空间注入
加入约束文件:xmlns:p="http://www.springframework.org/schema/p"
	<!--p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.he.pojo.User" p:name="柳柳" p:age="25"/>

4.3.2 c 命名空间注入
加入约束文件: xmlns:c="http://www.springframework.org/schema/c"
	<!--c命名空间注入,通过构造器注入。如果爆红需要在实体类添加有参构造方法-->
    <bean id="user2" class="com.he.pojo.User" c:name="问问" c:age="23"/>

二者都需要 需要在头文件中加入约束文件

4.4 Bean的作用域

4.4.1 单例模式(singleton)

Spring默认机制

 <bean id="user2" class="com.he.pojo.User" c:name="问问" c:age="23" scope="singleton"/>
4.4.2 原型模式(prototype)

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

  <bean id="user2" class="com.he.pojo.User" c:name="问问" c:age="23" scope="prototype"/>

5. Bean的自动装配

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

在Spring中有三种装配的方式:

  • 在xml中显示的配置

  • 在java中显示的配置

  • 隐式的自动装配bean【重要】

5.1测试

实体类:

public class People {
    private Cat cat;
    private Dog dog;
    private String name;
}
//ps:自行添加getter、setter、toString()方法。

public class Cat {
    public void bark() {
        System.out.println("miao~");
    }

}

public class Dog {
    public void bark() {
        System.out.println("wang~");
    }
}

applicationContext.xml文件:
    <bean id="people" class="com.he.pojo.People" >
      <property name="name" value="肖和"/>
      <property name="cat" ref="cat"/>
      <property name="dog" ref="dog"/>
    </bean>
测试类:
     @Test
    public void test1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        People people = context.getBean("people",People.class);
        people.getCat().bark();
        people.getDog().bark();
    }

5、Bean的自动装配

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

在Spring中有三种装配的方式:

  • 在xml中显示的配置

  • 在java中显示的配置

  • 隐式的自动装配bean【重要】

5.1测试

实体类:

public class People {
    private Cat cat;
    private Dog dog;
    private String name;
}
//ps:自行添加getter、setter、toString()方法。

public class Cat {
    public void bark() {
        System.out.println("miao~");
    }

}

public class Dog {
    public void bark() {
        System.out.println("wang~");
    }
}

applicationContext.xml文件:
    <bean id="cat" class="com.he.pojo.Cat"/>
    <bean id="dog111" class="com.he.pojo.Dog"/>
    <bean id="people" class="com.he.pojo.People" >
      <property name="name" value="肖和"/>
      <property name="cat" ref="cat"/>
      <property name="dog" ref="dog"/>
    </bean>
测试类:
     @Test
    public void test1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        People people = context.getBean("people",People.class);
        people.getCat().bark();
        people.getDog().bark();
    }

5.2 byName

    <!--
    byName:会自动在容器上下文中查找,和自己对象set方法后面对应值的bean id
    如:public void setCat(Cat cat) setCat的Cat
    -->
    <bean id="people" class="com.he.pojo.People" autowire="byName">
        <property name="name" value="肖和"/>
    </bean>

5.3 byType

    <!--
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
	如:<bean id="dog111" class="com.he.pojo.Dog"/> 只要class类型相同,甚至可以不用写bean的id
	但是要是有相同的类型出现就会报错。
    -->
    <bean id="people" class="com.he.pojo.People" autowire="byType">
        <property name="name" value="肖和"/>
    </bean>

byName使用时要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致。

byName使用时要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型值一致。

5.4 注解实现自动装配

要使用注解:(@Autowired)

  • 导入约束:context约束
  • 配置注解的支持【重点】
<?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>
  • 直接在属性上使用,也可以在set方式上使用!

  • 使用@Autowired我们可以不用编写Set方法了,但前提是你这个自动装配的属性在IOC容器中存在,且符合名字byName。

  • @Autowired是默认先通过byType注入,如果有多个类型后使用@Qualifer(value=“xxx”)指定一个唯一的bean对象注入,其实相当于是通过byName注入的。

实体类:
public class People {
    @Autowired
    @Qualifier(value = "cat111")
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;

    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    public String getName() {
        return name;
    }
}

xml文件:
<bean id="cat" class="com.he.pojo.Cat"/>
<bean id="cat111" class="com.he.pojo.Cat"/>
<bean id="cat222" class="com.he.pojo.Cat"/>
<bean id="dog" class="com.he.pojo.Dog"/>
<bean id="people" class="com.he.pojo.People"/>

6、使用注解开发

在Spring4之后要使用注解开发,要导入AOP的包

6.1 bean

配置扫描哪些包下的注解

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

在指定包下编写类,增加注解

//等价于    <bean id="user" class="com.he.pojo.User"/>
@Component
public class User {
    public String name ;
}

6.2 属性如何注入

直接在直接名上添加@value("值")

@Component
public class User {
    //相当于        <property name="name" value="yy"/>
    @Value("yy")
    public String name ;
}

如果提供了set方法,在set方法上添加@value("值");

@Component("user")
public class User {
	public String name;
	@Value("yy")
	public void setName(String name) {
	this.name = name;
	}
}

6.3 衍生的注解

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

  • dao --------------【@Repository】
  • service-----------【@Service】
  • controller-------【@Controller】

这四个注解功能一样,都是代表将某个类注册到 Spring中装配。

6.4 自动装配注解

6.5 作用域

6.6 小结

xml与注解:

  • xml更加万能,使用与任何场合,维护简单方便
  • 注解只能在自己的类使用,维护相对复杂

xml与注解的最佳实践:

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 在使用过程中,必须让注解生效,就是要开启注解的支持
    <!--指定要扫描的包,这个包下的注解都会生效-->
    <context:component-scan base-package="com.he.pojo"/>
    <context:annotation-config/>

7、使用java的方式配置Spring

实体类

import org.springframework.stereotype.Component;

/*这个注解的意思是,这个类被Spring接管了,注册到了容器中*/
@Component
public class User {
    private String name;

    public User(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

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

配置文件

package com.he.config;
import com.he.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/*
这个也是Spring容器托管,注册到容器中,因为她本身就是一个@Conponent
* @Configuration代表这是一个配置类,就和我们之前看的beans.xml一样
* */
@Configuration
@ComponentScan("com.he.pojo")
public class config {
    /*
    注册一个bean,就相当于我们之前写的一个bean标签
    * 这个方法的名字,就相当于我们之前bean标签中的id属性
    * 这个方法的返回值,就相当于bean标签中的class属性
    * */
    @Bean
    public User getUser() {
        return new User("哈哈哈");//就是要返回注入到bean的对象
    }
}

测试类

    @Test
    public void test01() {
        /*如果完全使用了配置类方式去坐,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载*/
        ApplicationContext context = new AnnotationConfigApplicationContext(config.class);
        User user = context.getBean("getUser", User.class);
        System.out.println(user.getName());
    }

这种方式在SpringBoot中随处可见

8、代理模式

代理模式是SpringAOP的底层

代理模式的分类:

  • 静态代理
  • 动态代理

8.1 静态代理

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

接口:

//租房
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();
        hetong();
        fare();
    }
    //看房
    public void SeeHouse() {
        System.out.println("中介带你看房");
    }

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

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

客户:

public class Client {
    public static void main(String[] args) {
        //房东要出租房子
        Host host = new Host();
        //代理,中介帮忙,并且还会有一些附属操作
        Proxy proxy = new Proxy(host);
        //你通过中介获取房屋信息
        proxy.rent();
    }
}
8.1.3 代理模式

优点:

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

缺点:

  • 一个真实角色就会产生一个代理角色,代码量对,且开发效率会变低

8.2 动态代理

  • 与静态代理的角色一样
  • 代理类是动态生成的
  • 分为基于接口的动态代理和基于类的动态代理
    • 基于接口----JDK动态代理(我们在这里使用)
    • 基于类-------cglib
    • java字节码实现--javaasist

需要了解:Proxy:代理和InvocationHandler:调用处理,这两个类

Proxy:生成动态代理这个实例

InvocationHandler:调用处理程序,并返回结果

8.2.1 代码步骤

接口:

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

真实角色:

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

代理角色:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*我们会用这个类去自动生成代理类*/
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);
    }
    //处理代理实例并返回结果
    public 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("收中介费");
    }
}

客户:

import com.he.Demo03.ProxyInvocationHandler;

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就是动态生成的
        proxy.rent();
    }
}
8.2.2 动态代理的好处
  • 一个动态代理类代理的是一个接口,一般就是对应一类业务
  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共也就是交给代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态代理类可以代理多个类,只需实现同一个接口

9、AOP

使用AOP织入,需要导入一个依赖包。

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>

方式一:使用Spring的API接口【主要是SpringAPI接口实现】

  1. 编写业务接口和实现类:
public interface UserService {
         void add();
         void delete();
         void update();
         void query();
}
public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("增加了一个用户");
    }

    public void delete() {
        System.out.println("删除了一个用户");
    }

    public void update() {
        System.out.println("修改了一个用户");
    }

    public void query() {
        System.out.println("查询了一个用户");
    }
}
  1. 编写增强类

    前置增强

    public class Log implements MethodBeforeAdvice {
    //method : 要执行的目标对象的方法
    //objects : 被调用的方法的参数
    //Object : 目标对象
    @Override
    public void before(Method method, Object[] objects, Object o) throws
    Throwable {
    System.out.println( o.getClass().getName() + "的" + method.getName()+ "方法被执行了");
    }
    

    后置增强

    public class AfterLog implements AfterReturningAdvice {
        //returnValue:返回值
        public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("执行了"+method.getName()+"的方法,返回结果为:"+returnValue);
        }
    }
    
  2. 去spring的文件中注册 , 并实现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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.kuang.service.UserServiceImpl"/>
<bean id="log" class="com.kuang.log.Log"/>
<bean id="afterLog" class="com.kuang.log.AfterLog"/>
<!--aop的配置-->
<aop:config>
<!--切入点 expression:表达式匹配要执行的方法-->
<aop:pointcut id="pointcut" expression="execution(*
com.kuang.service.UserServiceImpl.*(..))"/>
<!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
  1. 测试
public class myTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.query();
    }
}

Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理。

方式二:自定义来是实现AOP【主要是切面定义】

  1. 写一个切入类
public class DiyPointCut {
    public void before(){
        System.out.println("=====方法执行前=====");
    }
    public void after(){
        System.out.println("=====方法执行后=====");
    }
}
  1. 去Spring中配置
<!--方式二:自定义类-->
    <!--注册-->
    <bean id="diy" class="com.he.diy.DiyPointCut"/>
    <aop:config>
        <!--自定义切面,ref要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->;
            <aop:pointcut id="point" expression="execution(* com.he.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解实现AOP

  1. 编写一个注解实现的增强类
@Aspect
public class AnnotationPointcut {
@Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("---------方法执行前---------");
}
@After("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("---------方法执行后---------");
}
@Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
System.out.println("签名:"+jp.getSignature());
//执行目标方法proceed
Object proceed = jp.proceed();
System.out.println("环绕后");
System.out.println(proceed);
}
}
  1. 在Spring配置文件中,注册bean,并增加支持注解的配置
    <!--方式三-->
    <bean id="annotionPointCut" class="com.he.diy.AnnotationPonitCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>

posted on 2023-04-13 16:33  hemk  阅读(29)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3