AOP使用和配置
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层AopTestDaopublic AopTestDao getAopTestDao() {return aopTestDao;} @Resourcepublic 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@Componentpublic 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 {@Testpublic 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........
?
搞定
?
?
?
?