package before_package; import org.springframework.stereotype.Component; @Component("hello") public class Hello { public void sayHello(String a, String b) { System.out.println(a + ", " + b); } }
然后是一个使用@Aspect注解的类AuthAspect,指定了对特定方法的增强处理。
@Aspect public class AuthAspect { @Before("execution(* before_package.*.*(..))") public void before() { System.out.println("before"); } }
最后是测试类SpringTest,用于验证切面是否生效。
package test_spring_aop_package; import before_package.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext applicatiOnContext= new ClassPathXmlApplicationContext("beans.xml"); Hello hello = applicationContext.getBean("hello", Hello.class); hello.sayHello("Hello", "World"); } }