• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Java–简单的Spring AOP配置以及AOP事物管理,JDK/GCLib动态代理

java 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

一、看一下简单的通过XML的AOP配置

1.首先创建一个简单的Student类

public class Student {    private Integer age;    private String name;    public void setAge(Integer age) {        this.age = age;    }    public Integer getAge() {        System.out.println("Age : " + age);        return age;    }    public void setName(String name) {        this.name = name;    }    public String getName() {        System.out.println("Name : " + name);        return name;    }    public void printThrowException() {        System.out.println("Exception raised");        throw new IllegalArgumentException();    }}

2.创建一个简单的aspect切面class

public class Logging {/**     * This is the method which I would like to execute     * before a selected method execution.     */public void beforeAdvice() {        System.out.println("Going to setup student profile.");    }    /**     * This is the method which I would like to execute     * after a selected method execution.     */public void afterAdvice() {        System.out.println("Student profile has been setup.");    }    /**     * This is the method which I would like to execute     * when any method returns.     */    public void afterReturningAdvice(Object retVal) {        System.out.println("Returning:" + retVal.toString());    }    /**     * This is the method which I would like to execute     * if there is an exception raised.     */    public void AfterThrowingAdvice(IllegalArgumentException ex) {        System.out.println("There has been an exception: " + ex.toString());    }}

3.SpringAOP.xml配置

        <!---ecms XML方式配置Spring AOP-->               【切面class】             【切点】              【方法执行之前触发切面class的beforeAdvice方法】                【方法执行之后触发切面class的afterAdvice方法】            

分析一下这个execution(* com.seeyon.SpringBean.aop.Student.get*(..))切点表达式:

(1)第一个*代表方法的返回值是任意的

(2)get*代表以get开头的所有方法

(3)(..)代表方法的参数是任意个数

4.main方法

public class test {    p<em style="color:transparent">本文来源[email protected]搞@^&代*@码网(</em>ublic static void main(String[] args) {        ApplicationContext context =                new ClassPathXmlApplicationContext("SpringAop.xml");        Student student = (Student) context.getBean("student");        student.getName();//        student.getAge();//        student.printThrowException();    }}

5.输出结果

Going to setup student profile.Name : yangyuStudent profile has been setup.

二、Spring AOP注解的使用。

1.首先创建一个简单的Student类(同一.1中,请看上面


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java–简单的Spring AOP配置以及AOP事物管理,JDK/GCLib动态代理

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址