社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
AOP技术个人认为是能够完善(改善)面向对象编程OOP。为什么这么说,我们得先从AOP的概念说起,然后通过一段简单的例子加以佐证。这样子大家就可以慢慢地了解AOP
package com.spring.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
public class LogAop {
@Before("execution(public void com.spring.dao.impl.StudentDaoImpl.*(..))")
public void logBefore() {
System.out.println("方法执行之前加载日志");
}
}
package com.spring.dao;
public interface StudentDao {
public void insert();
}
package com.spring.dao.impl;
import com.spring.dao.StudentDao;
public class StudentDaoImpl implements StudentDao {
@Override
public void insert() {
System.out.println("method insert");
}
}
package com.spring.services;
import com.spring.dao.StudentDao;
public class StudentServices {
private StudentDao dao;
public void setDao(StudentDaodao) {
this.dao = dao;
}
public void insert() {
dao.insert();
}
}
package com.spring.junit;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.dao.StudentDao;
import com.spring.services.StudentServices;
public class Test_AOP {
@Test
public void testInsert() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
StudentServices ss = (StudentServices) ac.getBean("studentServices");
ss.insert();
}
}
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="studentServices" class="com.spring.services.StudentServices">
<property name="dao" ref="studentDao"></property>
</bean>
<bean id="studentDao" class="com.spring.dao.impl.StudentDaoImpl">
</bean>
<bean id="logAop" class="com.spring.aop.LogAop"></bean>
</beans>
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!