Spring中AOP的初窥和入门小案例

AOP:面向切面编程

  AOP的主要作用:是为了程序员更好的关注"业务",专心"做事"

    加上双引号的意思:所谓业务,是指他的核心,各行业中需要处理的核心事务,核心啊

    像日志的记录,事务的管理,权限分配等这些交叉业务,同一个项目中使用多次,直接提取出来成为公共的比较好,再用面向切面的方式,进行代码的编辑,业务的实现

AOP的原理 

 入门案例:

  用最基本的方式模拟一道日志的记录和最后执行完业务的操作

   DAO层(一个接口,一个他的实现类,模拟操作修改数据库)

package cn.dawn.day04aop.dao;
/**
 * Created by Dawn on 2018/3/5.
 *//*dao层接口*/public interface IHellowDAO {
    /*aop入门案例*/
    public void doSome();
}
package cn.dawn.day04aop.dao.impl;

import cn.dawn.day04aop.dao.IHellowDAO;
/**
 * Created by Dawn on 2018/3/5.
 *//*dao层实现类*/public class HellowDAOImpl implements IHellowDAO{

    public void doSome() {
        System.out.println("数据已经成功写入到DB");
    }
}

service层(也是一个接口,一个实现类,主要做的aop的增强操作,操作的是service层,业务逻辑处理层操作的)

package cn.dawn.day04aop.service;
/**
 * Created by Dawn on 2018/3/5.
 *//*service层接口*/public interface IHellowService {
    /*aop入门案例*/
    public void doSome();
}
package cn.dawn.day04aop.service.impl;

import cn.dawn.day04aop.dao.IHellowDAO;
import cn.dawn.day04aop.service.IHellowService;
/**
 * Created by Dawn on 2018/3/5.
 *//*service层实现类 */public class HellowServiceImpl implements IHellowService {
    IHellowDAO dao;
    public void doSome() {
        dao.doSome();
    }

    public IHellowDAO getDao() {
        return dao;
    }

    public void setDao(IHellowDAO dao) {
        this.dao = dao;
    }
}

 新开多的一层,叫aop层,他就存放了增强的操作(也就是交叉业务,例如日志记录等),此处我放了俩个类,一个执行前置增强,一个后置增强

package cn.dawn.day04aop.aop;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;
/**
 * Created by Dawn on 2018/3/5.
 *//*前置增强*/public class LoggerBefore implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("日志记录");
    }
}

package cn.dawn.day04aop.aop;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;
/**
 * Created by Dawn on 2018/3/5.
 *//*后置增强*/public class LoggerAfter implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("===============after==================");
    }
}

前置增强,需要实现MethodBeforeAdvice,后置增强,需要实现AfterReturningAdvice

接下来就是书写大配置xml文件

有个注意的点,由于我用的idea,他会自动生成上面的beans的 xmlns和xsi,如果你不是用idea的话,手动配置一道吧

 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" xmlns:aop="http://www.springframework.org/schema/aop"
 4        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">
 5
 6     <!--aop入门案例起-->
 7     <!--dao-->
 8     <bean id="dao" class="cn.dawn.day04aop.dao.impl.HellowDAOImpl"></bean>
 9     <!--service-->
10     <bean id="service" class="cn.dawn.day04aop.service.impl.HellowServiceImpl">
11         <property name="dao" ref="dao"></property>
12     </bean>
13     <!--通知-->
14     <bean id="afterAdvice" class="cn.dawn.day04aop.aop.LoggerAfter"></bean>
15     <bean id="beforeAdvice" class="cn.dawn.day04aop.aop.LoggerBefore"></bean>
16     <!--aop-->
17     <aop:config>
18         <!--切点-->
19         <aop:pointcut id="mypointcut" expression="execution(* *..service.*.*(..))"></aop:pointcut>
20         <!--<aop:pointcut id="mypointcut" expression="execution(public void cn.dawn.day04aop.service.IHellowService.doSome())"></aop:pointcut>-->
21         <!--<aop:pointcut id="mypointcut" expression="execution(* *..service.*.*(..))">-->
22         <!--顾问,织入-->
23         <aop:advisor advice-ref="beforeAdvice" pointcut-ref="mypointcut"></aop:advisor>
24         <aop:advisor advice-ref="afterAdvice" pointcut-ref="mypointcut"></aop:advisor>
25     </aop:config>
26     <!--aop入门案例完毕-->
27 </beans>

   这儿有一个切点pointcut,我说一下他的expression的属性吧,他就是里面放一个匹配的(可以说叫公式?)方法的公式

    他的使用规则我放在下面

  接下来单测方法

package cn.dawn.day04aop;

import cn.dawn.day03printer.printer.Printer;
import cn.dawn.day04aop.service.IHellowService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Created by Dawn on 2018/3/3.
 */public class test20180305 {
    @Test
    /*aop入门案例*/
    public void t01(){
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-day04aop.xml");
        IHellowService service = (IHellowService) context.getBean("service");
        service.doSome();
    }
}

 运行结果如下:

04.Spring的DI的构造注入,P命名注入,和集合注入 

DI和IOC相比,DI更偏向于实现

DI的set方式注入在前面入门案例里有写,所以此处不多啰嗦,直接开搞,先说构造注入和P命名注入

    构造方式,理所当然要有带参构造,这儿值得注意的是,你最好再补全一个无参构造,因为你写了带参构造,系统就不再会为你默认补全一个无参构造了,当你在不经意或者不知情的情况下被调用了,就会报错

    P命名则有注意的是那个头文件 xmlns  xsi需要你去配置一道,我下面有,你直接copy就可以

package cn.dawn.day05diup;
/**
 * Created by Dawn on 2018/3/5.
 */public class Car {
    private String color;
    private String type;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
package cn.dawn.day05diup;
/**
 * Created by Dawn on 2018/3/5.
 *///student类public class Student {
    private String name;
    private Integer age;
    private Car car;

    //带参构造
    public Student(String name, Integer age, Car car) {
        this.name = name;
        this.age = age;
        this.car = car;
    }

    //无参构造
    public Student() {
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }
}

在大配置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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">

    <bean id="car" class="cn.dawn.day05diup.Car">
        <property name="color" value="黑色"></property>
        <property name="type" value="奥迪"></property>
    </bean>
    <!--di构造注入-->
    <!--<bean id="student" class="cn.dawn.day05diup.Student">
        <constructor-arg index="0" value="孟六"></constructor-arg>
        <constructor-arg index="1" value="20"></constructor-arg>
        <constructor-arg index="2" ref="car"></constructor-arg>
    </bean>-->

    <!--p命名注入-->
    <bean id="student" class="cn.dawn.day05diup.Student" p:name="孟小六" p:age="8" p:car-ref="car"></bean>

</beans>

没有什么好讲的,带参构造的注入方法,index索引从0开始,对应的是那个带参构造的index

    单测方法:

@Test
    /*diP命名注入*/
    public void t02(){
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-day05diup.xml");
        Student student = (Student) context.getBean("student");
        System.out.println("学生"+student.getName()+"开着"+student.getCar().getColor()+"的"+student.getCar().getType());
    }

    @Test
    /*di构造注入*/
    public void t01(){
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-day05diup.xml");
        Student student = (Student) context.getBean("student");
        System.out.println("学生"+student.getName()+"开着"+student.getCar().getColor()+"的"+student.getCar().getType());
    }

集合注入:

    数组,List,Set,Map,Properties

  实体类

package cn.dawn.day05diup;

import java.util.*;
/**
 * Created by Dawn on 2018/3/5.
 */public class MyCollection {
    private String[] array;
    private List<String> list;
    private Set<String> set;
    private Map<String,String> map;
    private Properties properties;

    @Override
    public String toString() {
        return "MyCollection{" +
                "array=" + Arrays.toString(array) +
                ", list=" + list +
                ", set=" + set +
                ", map=" + map +
                ", properties=" + properties +
                ‘}‘;
    }

    public String[] getArray() {
        return array;
    }

    public void setArray(String[] array) {
        this.array = array;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Set<String> getSet() {
        return set;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}
大配置中的bean节点
 

<!--di的集合注入-->
    <bean id="mycollection" class="cn.dawn.day05diup.MyCollection">
        <!--数组注入-->
        <property name="array">
            <array>
                <value>孟六</value>
                <value>孟六十六</value>
                <value>孟六百六十六</value>
            </array>
        </property>
        <!--list集合注入-->
        <property name="list">
            <list>
                <value>奥迪</value>
                <value>奥小迪</value>
                <value>奥迪迪</value>
            </list>
        </property>
        <!--set集合注入-->
        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
                <value>set3</value>
            </set>
        </property>
        <!--map集合注入-->
        <property name="map">
            <map>
                <entry key="姓名">
                    <value>孟五</value>
                </entry>
                <entry key="年龄">
                    <value>555</value>
                </entry>
            </map>
        </property>
        <!--properties-->
        <property name="properties">
            <props>
                <prop key="key1">v1</prop>
                <prop key="key2">v2</prop>
                <prop key="key3">v3</prop>
            </props>
        </property>
    </bean>

单测

  @Test
    /*di集合注入*/
    public void t03(){
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-day05diup.xml");
        MyCollection mycollection = (MyCollection) context.getBean("mycollection");
        System.out.println(mycollection);
    }

 由于重写了toString,可以直接一览无余

这里我扩充一下 java 中的tostring();

toString()方法 相信大家都用到过,一般用于以字符串的形式返回对象的相关数据。

翻译一下官方解释:

 1、返回一个对于这个Object 简明的、可读的 的字符串

 2、Object类的子类被鼓励去重写这个方法来提供一个实现用于描述对象的类型和数据

自己的理解

写这个方法的用途就是为了方便操作,所以在文件操作里面可用可不用

就是一个类中有集合 当你输出这个集合时它会以

这种可以直接换算成字符串 十分的方便

如果没有 toString()    将会打印出来内存地址

更方便咱们程序员

原文地址:https://www.cnblogs.com/wh1520577322/p/9379873.html

时间: 2024-08-29 18:08:42

Spring中AOP的初窥和入门小案例的相关文章

Spring中AOP原理,使用笔记

AOP(面向切面编程):通过预编译和运行期动态代理的方式在不改变代码的情况下给程序动态的添加一些功能.利用AOP可以对应用程序的各个部分进行隔离,在Spring中AOP主要用来分离业务逻辑和系统级服务. 系统级服务指的是:事务处理,日志记录,性能统计,安全控制,异常处理等,因为这些功能分散在程序的各个模块中,又是通用的,所以可以将它从业务逻辑中分离出来. 连接点(joinpoint):在连接点可以拦截方法的执行,在连接点前后织入上述的这些系统级服务(织入的就是通知). 切入点(pointcut)

Spring中AOP简介与使用

Spring中AOP简介与使用 什么是AOP? Aspect Oriented Programming(AOP),多译作 "面向切面编程",也就是说,对一段程序,从侧面插入,进行操做.即通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术. 为什么要用AOP? 日志记录,性能统计,安全控制,事务处理,异常处理等等.例如日志记录,在程序运行的某些节点上添加记录执行操作状态的一些代码,获取执行情况.而通过切面编程,我们将这些插入的内容分离出来,将它们独立

Spring中AOP实例详解

Spring中AOP实例详解 需要增强的服务 假如有以下service,他的功能很简单,打印输入的参数并返回参数. @Service public class SimpleService { public String getName(String name) { System.out.println(get name is: + name); return name; } } 定义切面和切点 @Component @Aspect public class L ogAspect { // 定义切

spring boot入门小案例

spring boot 入门小案例搭建 (1) 在Eclipse中新建一个maven project项目,目录结构如下所示: cn.com.rxyb中存放spring boot的启动类,application.properties中放spring boot相关配置 (2) 在pom.xml中加入spring boot 依赖包 (3)在cn.com.rxyb中新建启动类APP 1 package cn.com.rxyb; 2 import org.springframework.boot.Spri

02SpringMvc_springmvc快速入门小案例(XML版本)

这篇文章中,我们要写一个入门案例,去整体了解整个SpringMVC. 先给出整个项目的结构图: 第一步:创建springmvc-day01这么一个web应用 第二步:导入springioc,springweb , springmvc相关的jar包 第三步:在/WEB-INF/下创建web.xml文件 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.

《Java从入门到放弃》入门篇:spring中AOP的配置方式

spring中最核心的两个东东,一个IOC,一个AOP. AOP(Aspect-OrientedProgramming)面向方面编程,也可以叫面向切面编程. 从一个新人的角度可以这样来理解:一般软件中的功能,我们可以分为两大类,一类是业务功能,一类是系统功能. 业务功能是指这个软件必须要用到的,没有的话客户就不给钱的.比如淘宝APP,如果你只能在上面浏览商品而不能购物,那就说明业务功能太监了···. 系统功能主要是指与业务无关,没有这块内容也不影响软件使用的.比如日志管理.权限处理等. AOP主

6.Spring中AOP术语与XML方式简单实现

1.AOP术语 1. Joinpoint(连接点):所谓连接点是指那些被拦截到的点.在spring中,这些点指的是方法,因为spring只支持方法类型的连接点 2. Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义 3. Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知.通知分为前置通知,后置通知,异常通知,最终通知,环绕通知(切面要完成的功能) 4. Introduction(引介):引介是一种特殊的通知在不修改类代

浅谈spring中AOP以及spring中AOP的注解方式

AOP(Aspect Oriented Programming):AOP的专业术语是"面向切面编程" 什么是面向切面编程,我的理解就是:在不修改源代码的情况下增强功能.好了,下面在讲述aop注解方式的情况下顺便会提到这一点. 一.搭建aop注解方式的环境(导入以下的包) 二.实现 环境搭建好了之后,就创建项目. 1.创建接口类(CustomerDao)并添加两个方法 2.接口类创建好了后,自然是要new一个实现类(CustomerDaoImpl)并实现接口中的方法 3.以上基础工作做完

Spring中AOP和IOC深入理解

spring框架 Spring框架是由于软件开发的复杂性而创建的.Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情.然而,Spring的用途不仅仅限于服务器端的开发.从简单性.可测试性和松耦合性的角度而言,绝大部分Java应用都可以从Spring中受益. ◆目的:解决企业应用开发的复杂性 ◆功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能 ◆范围:任何Java应用 Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器框架. Spr