AOP

反射

java创建对象的方法(5种):

Spring AOP:

spring分为:1、IOC/DI 2、AOP
AOP的使用场景:日志和事务
概念:AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

  • AOP核心概念
    1)Aspect(切面)
    2)Join Point(连接点)
    3)Advice(通知/增强)
    4)Pointcut(切点)
    5)Introduction(引入)
    6)Target Object(目标对象)
    7)AOP Proxy(AOP代理)
    8)Weaving(织入)
    代理模式的例子:

Move类

package com.spring;

public interface Move {
void move();
}

Car类

package com.spring;

public class Car implements Move {
@Override
public void move() {
System.out.println("Car is moving...");
}
}

Tank类

package com.spring;

public class Tank implements Move {
@Override
public void move() {
System.out.println("Tank is moving...");
}
}

TankProxy类

package com.spring;

public class TankProxy implements Move {
private Move t;

public TankProxy(Move t) {
    this.t = t;
}

@Override
public void move() {
    System.out.println("start");
    t.move();
    System.out.println("stop");
}

}

代理不能代理具体的类,得代理接口

MoveApp类

package com.spring;

public class MoveApp {
public static void main(String[] args) {
Move t1=new Tank();
Move t2=new Car();
Move moveProxy = new TankProxy(t2);
moveProxy.move();
}
}

运行结果

moveAPP.png

在pom.xml中添加了依赖(加上之前的总共五个)


UTF-8
1.8
1.8
5.1.5.RELEASE
1.9.2
4.12
1.2.17
1.7.12




org.aspectj
aspectjrt
{aspectj.version}



  org.springframework
  spring-context
  ${spring.version}




  org.springframework
  spring-aop
  ${spring.version}




  org.springframework
  spring-test
  ${spring.version}




  org.slf4j
  slf4j-api
  1.6.6


  org.slf4j
  slf4j-log4j12
  1.6.6


  

  junit
  junit
  4.12
  test

Hello的前置增强练习

Hello类

package com.spring;

public interface Hello {
String getHello();
}

HelloImpl

package com.spring;

public class HelloImpl implements Hello {
@Override
public String getHello() {
return "Hello,Spring AOP";
}
}

MyBeforeAdvice

package com.spring;

import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*

  • 用户自定义的前置增强类
  • /
    public class MyBeforeAdvice {
    private static final Logger logger= LoggerFactory.getLogger(MyBeforeAdvice.class);
    /
    定义前置方法*/
    public void beforeMethod() {
    logger.info("This is a before method ");
    logger.debug("This is a before method ");
   // System.out.println("This is a before methoad");
}

}

配置文件








    

HelloApp类

package com.spring;

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

public class HelloApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml");
Hello hello = context .getBean(Hello.class);
System.out.println(hello.getHello());
}

}

运行结果

hello.png

你可能感兴趣的:(AOP)