当前位置: 首页 > 编程日记 > 正文

Spring AOP与IOC以及自定义注解

Spring AOP实现日志服务


pom.xml需要的jar

<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.4</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.2.4.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.2.4.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>4.2.4.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>4.2.4.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.2.4.RELEASE</version>
</dependency>
<dependency><groupId>cglib</groupId><artifactId>cglib-nodep</artifactId><version>3.2.0</version>
</dependency>
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.8</version>
</dependency>
<dependency><groupId>aopalliance</groupId><artifactId>aopalliance</artifactId><version>1.0</version>
</dependency>
<dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2.2</version>
</dependency>
<dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version>
</dependency>


一.AOP用法一配置XML

1.Before Advice

Before Advice会在目标方法执行之前被调用,可以通过实现org.springframework.aop.MethodBeforeAdvice接口实现。

LogBeforeAdvice.java

package com.blog.csdn.net.unix21;import java.lang.reflect.Method;
import java.util.logging.Level;
import org.springframework.aop.MethodBeforeAdvice;
import java.util.logging.Logger;/**** @author http://blog.csdn.net/unix21/*/
public class LogBeforeAdvice implements MethodBeforeAdvice {private Logger logger=Logger.getLogger(this.getClass().getName());public void before(Method method,Object[] args,Object target) throws Throwable{logger.log(Level.INFO,"日志信息>>>method starts..."+method);}
}


beans-config.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="   http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd  http://www.springframework.org/schema/mvc   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> 
<bean id="LogBeforeAdvice" class="blog.csdn.net.unix21.LogBeforeAdvice"/>
<bean id="HelloSpeaker" class="blog.csdn.net.unix21.HelloSpeake"/>
<bean id="HelloProxy" class="org.springframework.aop.framework.ProxyFactoryBean"><property name="proxyInterfaces" value="blog.csdn.net.unix21.IHello"/><property name="target" ref="HelloSpeaker"/><property name="interceptorNames"><list><value>LogBeforeAdvice</value></list></property>
</bean>
</beans>

接口

IHello.java

package blog.csdn.net.unix21;public interface IHello {
public void hello(String name);
}

HelloSpeaker.java

package blog.csdn.net.unix21;public class HelloSpeaker implements IHello {public void hello(String name){System.out.println("Hello, "+name);}
}


测试Before Advice

SpringAOP 前置增强 后置增强 编程式 需XML配置

  ApplicationContext context=new ClassPathXmlApplicationContext("beans-config.xml");IHello h=(IHello)context.getBean("helloProxy");h.hello("blog.csdn.net.unix21")


运行成功使用AOP的方式打印日志信息:


参考:《Spring 2.0技术手册》

Spring 3.1编写AOP时需要导入的倚赖jar包汇总

菜鸟学SSH(七)——Spring jar包详解


2.After Advice

After Advice会在目标方法执行之后被调用,可以通过实现org.springframework.aop.AfterReturningAdvice接口来实现

import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.aop.AfterReturningAdvice;public class LogAfterAdvice  implements AfterReturningAdvice  {
private Logger logger=Logger.getLogger(this.getClass().getName());public void afterReturning(Object object, Method method, Object[] args, Object target) throws Throwable {logger.log(Level.INFO,"日志信息<<<method ends..."+method);}  
}

修改beans-config.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="   http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd  http://www.springframework.org/schema/mvc   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> 
<bean id="LogBeforeAdvice" class="blog.csdn.net.unix21.LogBeforeAdvice"/>
<bean id="HelloSpeaker" class="blog.csdn.net.unix21.HelloSpeake"/>
<bean id="HelloProxy" class="org.springframework.aop.framework.ProxyFactoryBean"><property name="proxyInterfaces" value="blog.csdn.net.unix21.IHello"/><property name="target" ref="HelloSpeaker"/><property name="interceptorNames"><list><value>LogBeforeAdvice</value><value>LogAfterAdvice</value></list></property>
</bean>
</beans>


成功的执行了LogAfterAdvice


二.AOP用法二编程式不配置XML

SpringAOP 前置增强 后置增强 编程式 无需XML配置

ProxyFactory pf=new ProxyFactory();
pf.setTarget(new TestModel());
pf.addAdvice(new LogBeforeAdvice());
pf.addAdvice(new LogAfterAdvice());
TestModel gt=(TestModel)pf.getProxy();
return gt.add(...);
效果是一样的。


三.Java自定义注解和运行时靠反射获取注解

还是日志信息,我们希望运行的时候可以获取自定义注解

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到  
@Target({ElementType.FIELD,ElementType.METHOD})//定义注解的作用目标**作用范围字段、枚举的常量/方法  
@Documented//说明该注解将被包含在javadoc中 
public @interface FieldMeta {/** * 是否为序列号 * @return */  boolean id() default false;  /** * 字段名称 * @return */  String name() default "";  /** * 是否可编辑 * @return */  boolean editable() default true;  /** * 是否在列表中显示 * @return */  boolean summary() default true;  /** * 字段描述 * @return */  String description() default "";  /** * 排序字段 * @return */  int order() default 0;  
}


声明注解



需要注意如果一个类是接口的实现,那么这种注解需要写接口方法上,例如AOP的调用方式一,对于AOP的调用方式二可以把注解写类的方法上即可。


调用

if (method.isAnnotationPresent(FieldMeta.class)) {FieldMeta myAnnotation = method.getAnnotation(FieldMeta.class);System.out.println("注解:" + myAnnotation.description() + " 类:"+target.getClass().getName()+" 方法:" + method.getName());
}




参考:Java自定义注解和运行时靠反射获取注解



相关文章:

小白也能看懂:一文学会入门推荐算法库 surprise

来源 | 机器学习与推荐系统surprise 支持的每个算法本身思路并不复杂&#xff0c;代码也不晦涩难懂&#xff0c;我们主要的目的是理解它的架构&#xff0c;学习框架各个部分的交互。这篇文章是想从一个整体的视角&#xff0c;以作者最初的思路为主线进行介绍&#xff0c;观察并…

开发人员必备网站

http://www.gotapi.com/语言&#xff1a;英语简介&#xff1a;HTML,CSS,XPATH,XSL,JAVASCRIPT等API的查询网站。http://www.w3schools.com/语言&#xff1a;英语简介&#xff1a;W3C制定的标准诸如XML,HTML,XSL等等的在线学习教程。http://www.xml.org.cn/语言&#xff1a;中文…

iOS实现依赖注入

依赖注入(Dependency Injection)这个词&#xff0c;源于java&#xff0c;但在Cocoa框架中也是十分常见的。举例来说&#xff1a;UIView的初始化方法initWithFrame - (id)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER; 这里的frame传入值&#xff0c;就是所谓的依赖(…

shell语法以及监控进程不存在重启

转码 # dos2unix ./test.sh 权限 # chmod ax ./test.sh语法变量var"111"echo $varecho ${var}运算no14;no25;let resultno1no2echo $result;自增自减少let no let no--[]和let类似result$[ no1 no2 ]result$[ $no1 5 ]也可以使用(())&#xff0c;但使用(())时&…

当莎士比亚遇见Google Flax:教你用​字符级语言模型和归递神经网络写“莎士比亚”式句子...

作者 | Fabian Deuser译者 | 天道酬勤 责编 | Carol 出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;有些人生来伟大&#xff0c;有些人成就伟大&#xff0c;而另一些人则拥有伟大。—— 威廉莎士比亚《第十二夜》在几个月前&#xff0c;谷歌的研究人员介绍了机器学习…

netbackup错误之can not connect on socket(25)

rhel5.5上安装netbackup 7.0&#xff0c;这个版本只能安装在64位系统上。安装完netbackup 7.0后&#xff0c;发现登录界面一直报java认证失败&#xff0c;查看了下日志文件&#xff0c;报如下内容&#xff1a; 查了下系统设置&#xff0c;发现/etc/hosts文件里的主机名对应的IP…

支撑Spring的基础技术:泛型,反射,动态代理,cglib等

1.静态代码块和非静态代码块以及构造函数 出自尚学堂视频&#xff1a;《JVM核心机制 类加载全过程 JVM内存分析 反射机制核心原理 常量池理解》 public class Parent {static String name "hello";//非静态代码块{System.out.println("1");}//静态代码块…

深度干货!如何将深度学习训练性能提升数倍?

作者 | 车漾&#xff0c;阿里云高级技术专家顾荣&#xff0c;南京大学副研究员责编 | 唐小引头图 | CSDN 下载自东方 IC出品 | CSDN&#xff08;ID&#xff1a;CSDNnews&#xff09;近些年&#xff0c;以深度学习为代表的人工智能技术取得了飞速的发展&#xff0c;正落地应用于…

VIM变IDE

2019独角兽企业重金招聘Python工程师标准>>> 根据这篇博文写了个脚本&#xff0c;简单的解压插件和复制配置&#xff0c;可以帮大家快速配置一个VIM。 脚本中使用rpm安装ctags&#xff0c;所以只支持redhat系的&#xff0c;debian系的要自己安装ctags. 脚本放在gith…

Netbeans使用maven下载源码

如果需要研究源码&#xff0c;自然需要下载源码&#xff0c;其实Netbeans使用maven构建项目下载源码非常简单。 springmvc一开始没有下载源码 commons-lang3是下了源码的&#xff0c;下面是对其调用的代码 可以看到点开其代码是源码&#xff0c;也可以打断点 开一个调试 下载源…

讯飞智能语音先锋者:等到人机交互与人类交流一样自然时,真正的智能时代就来了...

作者 | 夕颜出品 | CSDN&#xff08;ID:CSDNnews&#xff09;「AI 技术生态论」 人物访谈栏目是 CSDN 发起的百万人学 AI 倡议下的重要组成部分。通过对 AI 生态顶级大咖、创业者、行业 KOL 的访谈&#xff0c;反映其对于行业的思考、未来趋势的判断、技术的实践&#xff0c;以…

今天看到两个题 写出来思考一下

数组中已有升序的6个数,输入一个数插入到数组中该数组仍然升序. 1&#xff0c;6&#xff0c;9&#xff0c;23&#xff0c;56&#xff0c;95 输入一个数 50 输出 1&#xff0c;6&#xff0c;9&#xff0c;23&#xff0c;56&#xff0c;50&#xff0c;95 题目二 输入一个…

android开发之动画的详解 整理资料 Android开发程序小冰整理

2019独角兽企业重金招聘Python工程师标准>>> /** * 作者&#xff1a;David Zheng on 2015/11/7 15:38 * * 网站&#xff1a;http://www.93sec.cc * * 微博&#xff1a;http://weibo.com/mcxiaobing * * 微博&#xff1a;http://weibo.com/93sec.cc */ 个人交流QQ9…

框架源码学习笔记

1.WebListener Servlet3.0提供WebListener注解将一个实现了特定监听器接口的类定义为监听器&#xff0c;这样我们在web应用中使用监听器时&#xff0c;也不再需要在web.xml文件中配置监听器的相关描述信息了。 Web应用启动时就会初始化这个监听器 WebListener public class M…

20万个法人、百万条银行账户信息,正在暗网兜售

导语&#xff1a;推特用户爆料&#xff0c;暗网上正在出售大量中国数个银行的账号信息&#xff0c;经记者调查&#xff0c;本次打包售价 3999 美金中包含 90 万条中国农业银行账号信息&#xff0c;另外一账号还宣称出售二十个数据包&#xff0c;其中包括百万条银行账号数据、12…

2010年9月blog汇总:敏捷个人和模型驱动开发

9月份指标产品开发开始同时进行两个客户的开发&#xff0c;所以考虑了客户化如何开发的问题&#xff1b;在企业定额产品上&#xff0c;参与清单综合单价库的产品架构并做了用户调研前期准备工作&#xff1b;再就是整理了一下模型驱动开发理论以及思考了OpenExpressApp的几个建模…

Tomcat的配置及优化

Tomcat 服务器是基于Apache 软件基金会项目开发的一个免费的开放源代码的Web 应用服务器它是开发和调试JSP 程序的首选&#xff0c;主要用在中小型系统和并发访问用户不是很多的场合&#xff0c;实际Tomcat 部分是Apache 服务器的扩展&#xff0c;但它是独立运行的&#xff0c;…

JAX-WS Web 服务开发调用和数据传输分析

一. 开发服务 新建maven的web项目就可以了&#xff0c; 1.新建一个web服务 2.服务名称定义 3.更改配置 4.默认建好的服务文件 5.增加一个add的服务 import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam;/**** author Administrator*/ WebSer…

如何在高精度下求解亿级变量背包问题?

导读&#xff1a;国际顶级会议WWW2020将于4月20日至24日举行。始于1994年的WWW会议&#xff0c;主要讨论有关Web的发展&#xff0c;其相关技术的标准化以及这些技术对社会和文化的影响&#xff0c;每年有大批的学者、研究人员、技术专家、政策制定者等参与。以下是蚂蚁金服的技…

收集到的一些网络工程师面试题 和大家分享下

1: 交换机是如何转发数据包的?交换机通过学习数据帧中的源MAC地址生成交换机的MAC地址表&#xff0c;交换机查看数据帧的目标MAC地址&#xff0c;根据MAC地址表转发数据&#xff0c;如果交换机在表中没有找到匹配项&#xff0c;则向除接受到这个数据帧的端口以外的所有端口广播…

incompatible with sql_mode=only_full_group_by

使用mysql 5.7.11-debug Homebrew时报错 错误信息如下&#xff1a; 26 Mar 2016 09:35:23,432 ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper:147 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘tv2.t_pic_news…

Java动态加载一个类的几种方法以及invoke

一.加载一个类的几种方法 接口 IUser package org.me.javaapp;/**** author Administrator*/ public interface IUser {}User.java /** To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templ…

今晚20:00 | 港科大郑光廷院士详解人工视觉技术发展及应用

阳春三月&#xff0c;万象更新&#xff0c;2020年注定是不平凡的一年&#xff01;有激荡就会遇见变革&#xff0c;有挑战就会迎来机遇。今天总会过去&#xff0c;未来将会怎样&#xff1f;香港科大商学院内地办事处重磅推出全新升级的《袁老师访谈录》全新系列【问诊未来院长系…

Openoffice 安装与配置

1、软件下载 路径&#xff1a;http://download.openoffice.org/ 2、软件安装 [rootOpenbo linux]# tar zxvf OOo_3.2.1_Linux_x86_install-rpm-wJRE_zh-CN.tar.gz[rootOpenbo linux]# cd OOO320_m18_native_packed-1_zh-CN.9502/[rootOpenbo OOO320_m18_native_packed-1_zh-CN.…

比较分析与数组相关的sizeof和strlen

// 形如&#xff1a; int a[]{1,2,3,4,5}; char name[]"abcdef";无论是整型数组还是字符数组&#xff0c;数组名作为右值的时候都代表数组首元素的首地址。数组发生降级&#xff08;数组名退化为数组首元素的地址&#xff09;的情况&#xff1a;数组传参、数组名参与…

Python正则表达式,看这一篇就够了

作者 | 猪哥来源 | 裸睡的猪&#xff08;ID: IT--Pig&#xff09;大多数编程语言的正则表达式设计都师从Perl&#xff0c;所以语法基本相似&#xff0c;不同的是每种语言都有自己的函数去支持正则&#xff0c;今天我们就来学习 Python中关于 正则表达式的函数。re模块主要定义了…

Spring MVC 4

Spring MVC 4 项目文件结构 pom.xml依赖 <properties><endorsed.dir>${project.build.directory}/endorsed</endorsed.dir><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies> …

SQL Server 2008高可用性系列:数据库快照

SQL Server 2008高可用性系列&#xff1a;数据库快照http://database.51cto.com 2010-09-13 14:45 我爱菊花 博客园 我要评论(0)摘要&#xff1a;我们今天要讨论的话题是数据库快照。在SQL Server 2008高可用性中&#xff0c;快照是一项很重要的内容&#xff0c;可以提供至…

PostgreSQL 9.3 beta2 stream replication primary standby switchover bug?

[更新]已有patch. 请参见.PostgreSQL 9.1,9.2,9.3 clean switchover Primary and Standby Patch. http://blog.163.com/digoal126/blog/static/16387704020136197354054/打补丁前的测试 : PostgreSQL 9.3 beta2 无法完成正常的主备角色切换.Primary : psql checkpont; pg_cont…

Apache commons-io

添加引用 <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency>按行写&#xff1a; public static void writeFileLineByApacheIO(String fileContent) throws…