定义一个接口
java 代码
- package com.tyq.spring.aop.annotation;
-
- public interface Say {
- void say();
- void say(String str);
- String say(String str,int i);
- }
实现接口
java 代码
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
-
- public class SayImpl implements Say {
- private static final Log log = LogFactory.getLog(SayImpl.class);
- @Override
- public void say() {
- System.out.println(this.getClass().getMethods()[0]);
-
- }
-
- @Override
- public void say(String str) {
- System.out.println(this.getClass().getMethods()[0]);
-
- }
-
- @Override
- public String say(String str, int i) {
- System.out.println(str + i);
- return str;
- }
-
- }
@Aspect的定义
java 代码
- package com.tyq.spring.aop.annotation;
-
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.aspectj.lang.annotation.AfterReturning;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Pointcut;
-
- @Aspect
- public class AopAfterReturning {
- @Pointcut("execution(* Say.*(..))")
- public void test(){
- System.out.println("hello");
- }
- @AfterReturning("test()")
- public void afterTest()
- {
- System.out.println(this.getClass());
- }
- }
applicationContex.xml配置文件
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:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
- <aop:aspectj-autoproxy/>
- <bean id="aspect" class="com.tyq.spring.aop.annotation.AopAfterReturning"/>
- <bean id="sayImpl" class="com.tyq.spring.aop.annotation.SayImpl"/>
- <!---->beans>
主函数入口
java 代码
- package com.tyq.spring.aop.annotation;
-
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class TestMain {
-
-
-
-
- protected static Log log = LogFactory.getLog(TestMain.class);
- public static void main(String[] args){
- ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml",TestMain.class);
- Say test = (Say)context.getBean("sayImpl");
- test.say();
- test.say("how are you!");
- test.say("who are you !", 2);
- log.info("hello");
- }
-
- }