基于Spring框架的切面编程

基于Spring框架的切面编程

拦截指定执行的方法,在方法执行前后做一些操作,防止你忘了什么操作,忘关流之类的,造成线程堵塞

AOP  aspect orient programing  面向切面编程,这个demo是基于上一篇博客 Spring依赖注入的demo写的,要引入的jar包:


两种配置方式   一种基于注解  一种基于xml配置

SpringAop基于注解方式:
首先要配置aop的xml,要加入三行代码在application-context.xml的标签头
  http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"
        xmlns:aop="http://www.springframework.org/schema/aop

applicaiton-context.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
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
>
  <context:component-scan base-package="com.dengweiquan.**"/>
    <bean id="user" class="com.dengweiquan.entity.User">
        <!--Spring用运行时会通过这个配置文件,加载这个bean,用反射创建这个bean,我们就不用创建对象就可以用到这个属性了-->
        <!--<constructor-arg type="int" value="12345"></constructor-arg>-->
        <!--<constructor-arg type="java.lang.String" value="laowang"></constructor-arg> -->
        <property name="id" value="12345"/>
        <property name="name" value="laowang" />
    </bean>
    <bean id="fatherUser" class="com.dengweiquan.entity.UserFather">
        <property name="fatherName" value="laodie"/>
        <!--ref里面user的意思是  这个bean参考user的bean-->
        <property name="user" ref="user"/>
    </bean>

    <!--<aop:aspectj-autoproxy/>   的意思是自动检测我们设置的切面,自动代理-->
    <aop:aspectj-autoproxy/>
</beans>

UserController类:
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}

User类:
public class User {
    private int id;
    private String name;
    public User(){
    }
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

UserFather类:
public class UserFather {
    private String fatherName;
    private User user;
    public String getFatherName() {
        return fatherName;
    }
    public void setFatherName(String fatherName) {
        this.fatherName = fatherName;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}

UserService类:
@Service
public interface UserService {
    public String  say(String value);
}


UserServiceImpl类:
@Service()
public class UserServiceImpl implements UserService {
    @Override
    public String  say(String value) {
        System.out.println("成功运行"+value);
        return "我是返回值";
    }
}

主函数:
public class Main {
    public static void main(String[] args) {
        //拿到spring上下文  就拿到spring的bean了
        ApplicationContext context=new ClassPathXmlApplicationContext("./com/dengweiquan/resource/application-context.xml");
//        UserFather userFather=(UserFather) context.getBean(UserFather.class);
//        System.out.println(userFather.getFatherName());//输出12345
        //spring注解方式注入  MVC  model view controller
       // @Service  业务逻辑
        //@Component  公共组件
        //@Controller   控制用户请求  springMVC

        UserController userController=context.getBean(UserController.class);
         UserService service= userController.getUserService();
        service.say("laowang");
    }
}


创建一个名为aop的包 右键新建UserAspcet类
@Component
@Aspect  //声明切面
public class UserAspect {
    //设置切点    概念:告诉spring容器,aop是要在什么地方切入,是拦截什么方法?拦截那个包下面的方法?
    // @Pointcut 里的value参数实际是个正则表达式 这个是个死套路,可以记下来
    //execution(* com.dengweiquan.service.*.*(..))   意思是*你要拦截的包.包下的所有类,所有类下的方法
    //告诉切点  你要拦截那个地方的全部方法
    @Pointcut(value = "execution(* com.dengweiquan.service.*.*(..))")
    public void pointCut(){
    }
    //advice  拦截前要干什么事情,什么时候干
    @Before(value = "pointCut()")
    public void doBefore(JoinPoint joinPoint){
        //JoinPoint  是连接点(程序执行的点,拿到执行拦截的那个点的方法)
        //拿到方法的名称
         String name= joinPoint.getSignature().getName();
         //拿到方法的参数
        Object[] args=    joinPoint.getArgs();
        System.out.println(name+"  "+args.toString());   //输出say  [Ljava.lang.Object;@72d1ad2e
    }
    //执行成功  输出 成功运行laowang
    //拦截后要干什么事情
    @After(value = "pointCut()")
    public void doAfter(JoinPoint joinPoint){
        String name= joinPoint.getSignature().getName();
        //拿到方法的参数
        Object[] args=    joinPoint.getArgs();
        System.out.println(name);  //输出say
    }
   
   //result是拿到方法的返回值
    @AfterReturning(value = "pointCut()",returning ="result" )
    public void  afterReturning(JoinPoint joinPoint,Object result){

        //拦截方法的返回值
        System.out.println(result);  //输出我是返回值
    }
    //抛异常的时候
    @AfterThrowing()
    public void afterThrowing(){
    }
    //环绕通知  控制方法的执行
    @Around(value = "pointCut()")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //推进方法执行点  ProceedingJoinPoint  假如弄了环绕通知,不执行proceedingJoinPoint.proceed();  就会拦截这个方法,就不输出成功运行laowang
        //全程监控方法执
        proceedingJoinPoint.proceed();   //输出成功运行laowang
    }
}

SpringAop基于xml:

先创建Logger类:
public class Logger {
  //设置为环绕通知
    public void doLog(ProceedingJoinPoint proceedingJoinPoint){
        try {
            proceedingJoinPoint.proceed();  //不运行这句就不会输出成功运行laowang
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

    }
}


application-context.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
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
>

    <context:component-scan base-package="com.dengweiquan.**"/>
    <bean id="user" class="com.dengweiquan.entity.User">
        <!--Spring用运行时会通过这个配置文件,加载这个bean,用反射创建这个bean,我们就不用创建对象就可以用到这个属性了-->
        <!--<constructor-arg type="int" value="12345"></constructor-arg>-->
        <!--<constructor-arg type="java.lang.String" value="laowang"></constructor-arg> -->
        <property name="id" value="12345"/>
        <property name="name" value="laowang" />
    </bean>
    <bean id="fatherUser" class="com.dengweiquan.entity.UserFather">
        <property name="fatherName" value="laodie"/>
        <!--ref里面user的意思是  这个bean参考user的bean-->
        <property name="user" ref="user"/>
    </bean>
    <!--<aop:aspectj-autoproxy/>   的意思是自动检测我们设置的切面,自动代理-->
    <!--<aop:aspectj-autoproxy/>-->

    <bean id="loger" class="com.dengweiquan.aop.Logger"></bean>
    <!--用xml的方式声明切面-->
    <aop:config>
        <!--ref里面填的是要参考的bean-->
        <aop:aspect id="logAspect" ref="loger" >
            <aop:around method="doLog" pointcut="execution(* com.dengweiquan.service.*.*(..))"/>
        </aop:aspect>
    </aop:config>
</beans>

项目目录结构:




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值