在学spring的时候 初学aop面向切面编程的时候,书上讲的很简单就是对一段业务添加一段逻辑,我就尝试着自己写了一个对service添加一段逻辑,就是在执行service的一段代码的时候在让其执行另一端代码,例如一下的例子:
package com.qbd.blog.serviceimpl;
import java.util.Date;
import javax.annotation.Resource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import com.qbd.blog.dao.LogDao;
import com.qbd.blog.model.Log;
import com.qbd.blog.service.LogService;
@Aspect
@Component("logService")
public class LogServiceImpl implements LogService {
private LogDao logDao;
public LogDao getLogDao() {
return logDao;
}
@Resource
public void setLogDao(LogDao logDao) {
this.logDao = logDao;
}
public boolean add(Log log) {
// TODO Auto-generated method stub
return logDao.add(log);
}
@Pointcut("execution(public boolean com.qbd.blog.serviceimpl..ArticleServiceImpl.*(..))")//给切入点起一个别名(必须是方法)
public void mymethod(){};
@After("mymethod()")
public void before(JoinPoint point){
String methodname=point.getSignature().getName();
methodname=methodname+"execute";
Log log=new Log();
log.setContent(methodname);
log.setDate(new Date());
add(log);
}
}
利用注解给@Pointcut("execution(public boolean com.qbd.blog.serviceimpl..ArticleServiceImpl.*(..))")//给切入点起一个别名(必须是方法)这个方法添加一段逻辑,在执行ArticleServiceImpl这个类里面的方法的时候会在他们之前都执行 public void before(JoinPoint point){
String methodname=point.getSignature().getName();
methodname=methodname+"execute";
Log log=new Log();
log.setContent(methodname);
log.setDate(new Date());
add(log);
}这段代码
其实spring自己本身就用到了aop例如为service添加事务