首先建立xml文档beans.xml


       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
          http://www.springframework.org/schema/aop
          
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

(红色部分为aop所必需引入的)
 
 
  (aop 自动代理)

建立aop包,建立LogInterceptor.java

package com.chpn.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogInterceptor {
 @Before("execution (public * com.chpn.dao.impl.UserDAOImpl.save(com.chpn.model.User))")
 public void before(){
  System.out.println("Before method");
 }
}

在各个类上加注解

UserDaoImpl.java

package com.chpn.dao.impl;

import org.springframework.stereotype.Component;

import com.chpn.dao.UserDAO;
import com.chpn.model.User;

@Component("u")
public class UserDAOImpl implements UserDAO {

 @Override
 public void save(User u) {
  System.out.println("user save");
 }

}

UserService.java

 

package com.chpn.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.chpn.dao.UserDAO;
import com.chpn.model.User;

@Component("userService")
public class UserService {
 public UserDAO userDAO;

 public void add(User user) {
  
  userDAO.save(user);
 }

 public UserDAO getUserDAO() {
  return userDAO;
 }
 @Resource(name="u")
 public void setUserDAO(UserDAO userDAO) {
  this.userDAO = userDAO;
 }

}

 Test.class


public class Test {
 public static void main(String args[]){
  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  
  UserService service = (UserService)ctx.getBean("userService");
  System.out.println(service.getClass());
  service.add(new User());
  
  ctx.destroy();
 }
}