---
title: "AOP使用和配置"
author: "xiaofengxbf"
date: "2013-11-13T17:57:42Z"
tags: []
categories: ["企业架构"]
slug: "aop"
draft: false
lastmod: "2013-11-13T17:57:42Z"
id: 1974416
url: "https://xiaofengxbf.iteye.com/blog/1974416"
---

AOP使用代码:

一、Dao层

 接口：AopTestDao

 

```
package com.sshcp.dao;

public interface AopTestDao {
	public void aopTest();
}
```

 实现类：AopTestDaoImpl

 

 

```
package com.sshcp.dao.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.sshcp.dao.AopTestDao;

@Component("aopTestDao")
public class AopTestDaoImpl implements AopTestDao {
	
	public void aopTest() {
		// TODO Auto-generated method stub
		   System.out.println("dao 层 ");
	
	}
}
```

 

 

service层：

接口类：AopServiceI

 

```
package com.sshcp.service.aopi;

public interface AopServiceI {
	
	public void aopTestMothod();

}
```

 实现类：AopServiceImpl

 

 

```
package com.sshcp.service.aopi.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.sshcp.dao.AopTestDao;
import com.sshcp.service.aopi.AopServiceI;

@Component("aopServiceI")
public class AopServiceImpl implements AopServiceI {
   
	private AopTestDao aopTestDao ;  // 注入dao层AopTestDao
	
	public AopTestDao getAopTestDao() {
		return aopTestDao;
	}
    
	@Resource
	public void setAopTestDao(AopTestDao aopTestDao) {
		this.aopTestDao = aopTestDao;
	}


	public void aopTestMothod() {
		// TODO Auto-generated method stub
   		System.out.println("aop test service here ");
      
	}

}
```

 

 

切面类：AspectTest

 

```
package com.sshcp.aspect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@org.aspectj.lang.annotation.Aspect
@Component
public  class AspectTest {
     
	@Pointcut("execution(* com.sshcp.service.aopi.impl.AopServiceImpl.aop*(..)))")
	public void testMothod(){
	}
	
	@Before("testMothod()")
	public void beforeMothe(){
		System.out.println("121212121212121212 Before.......");
	}
	
	@After("testMothod()")
	public void afterMothe(){
		System.out.println("2323232323232323232 After........");
	}
}

```

 

Spring xml 中加入如下配置：

```
       <context:annotation-config />
       <aop:aspectj-autoproxy />
       <context:component-scan base-package="com.sshcp" />
```

 

测试代码：

```
package com.hibernate.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sshcp.service.aopi.AopServiceI;

public class AopTest {
	
	@Test
	public void test(){
		ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext-c3p0.xml");
		AopServiceI as = (AopServiceI)app.getBean("aopServiceI");
		as.aopTestMothod();
	}
}

```

 

测试打印出的信息：

121212121212121212 Before.......  
aop test service here  
2323232323232323232 After........

 

搞定