承接上一次的入门学习,这次使用注解的方式实现AOP!
就是下面的@Component("service")了
1.注解配置业务类
package com.cqu.service;
import org.springframework.stereotype.Component;
@Component("service")
public class Person_dbservice {
public void doSomeService() {
System.out.println("二狗子要登录了");
}
}
2.注解配置切面
相关解释:
@Aspect注解表示这是一个切面
@Component注解表示这是一个bean,由Spring管理
注意!
@Around(value="execution(* com.cqu.service.Person_dbservice.*(..))")表示对com.cqu.service.Person_dbservice这个类中的所有方法进行切面操作
package com.cqu.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggerAspect {
//注意以下注解方式,表示执行Person_dbservice类中的任意方法(该方法传入任意数量任意类型的参数),
//第一个*表示返回值任意
@Around(value="execution(* com.cqu.service.Person_dbservice.*(..))")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("start log:"+joinPoint.getSignature().getName());
Object object=joinPoint.proceed();
System.out.println("end log:"+joinPoint.getSignature().getName());
return object;
}
}
3.配置applicationContext.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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.cqu.service"></context:component-scan>
<context:component-scan base-package="com.cqu.aspect"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
主要是下面这几句:
<context:component-scan base-package="com.cqu.service"></context:component-scan>
<context:component-scan base-package="com.cqu.aspect"></context:component-scan>
扫描包com.cqu.servicce和com.cqu.aspect,定义业务类和切面类
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
4.测试结果:
package com.cqu.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cqu.service.Person_dbservice;
public class My_test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Person_dbservice person_dbservice = (Person_dbservice) context.getBean("service");
person_dbservice.doSomeService();
}
}
结果如下:
start log:doSomeService
二狗子要登录了
end log:doSomeService
可以看出结果和上次是一样的,只是用到的技术不一样(注解方式)