您的位置:首页 > 编程语言 > Java开发

spring的AOP个人理解和使用

2015-04-14 22:34 681 查看
1什么是AOP:AOP是面向切面编程,也就是说面向某个功能模块编程,典型的应用就是Spring的声明式事务,
Spring的AOP事务解析:
在以前的事务管理是要融合在逻辑代码中的,在逻辑代码中决定事务是否提交或者回滚,这样很容易造成代码难以维护,代码冗余
但是使用spring的声明式事务后,只需要在数据库处理方法上注解事务,就可以对操作进行管理,事务的设置和逻辑代码分开,容易维护
2AOP有什么作用
:面向切面编程,例如某个功能点,我们只需抽取横切关注点,然后让需要处理这些功能点的方法来使用代理的方式调用

3AOP有什么组成
1切面:横切关注点被模块化的对象---功能模块化组成的对象
2通知:就是切面需要完成的功能---就是功能的实现方法1、方法2...
3连接点:就是程序执行的某个特定位置,例如方法前方法后,也是通知所关心的位置
4目标:被通知的对象,也是连接点所在的对象
5代理(Proxy): 向目标对象应用通知之后创建的对象
4AOP怎样使用
1:抽取横切关注点:也就是抽取我们需要面向切面编程的功能,然后模块化对象
2:然后把模块化对象声明为切面
3:把模块对象细粒化,把功能细分为各个方法
4:声明通知和通知的连接点
登录示例:

登录前后需要调用某一个动能---->也就是横切关注点
 1切面:横切关注点模块化的对象--》loginCheck

package com.aop;

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

@Aspect
@Component
public class LoginCheck {

public void beforeLogin() {
System.out.println("登录前检查---------->");
}

public void afterLogin() {
System.out.println("登录后检查---------->");
}
}


2把模块对象的功能细粒化,细分为各个方法上面代码已经细化粒化的

3声明通知和连接点:

@Before(value ="execution(* com.aop.entityService.*(..))")
public void beforeLogin(JoinPoint joinPoint) {
System.out.println(joinPoint.getSignature().getName()+"登录前检查---------->");
}

@After(value ="execution(* com.aop.entityService.*(..))")
public void afterLogin(JoinPoint joinPoint) {
System.out.println(joinPoint.getSignature().getName()+"登录后检查---------->"+joinPoint.getStaticPart().getSignature().getDeclaringType().getName());
}

login类:

package com.aop;

import org.springframework.stereotype.Repository;

@Repository
public class entityService {

private int id;
private String name="jeremy";

public void login() {
System.out.println(this.name+"登录了------>");
}

}


测试代码:

public static void main(String[] args) throws SQLException {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
entityService entityService=applicationContext.getBean(entityService.class);
entityService.login();
}


测试:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: