Spring学习

5.Spring中的AOP

2019-03-09  本文已影响0人  长生藤

AOP的定义

AOP基本上是通过代理机制实现的,他是OOP的延续也是spring框架中最重要的内容之一.

AOP中基本概念

AOP代理

Spring AOP默认使用标准的JDK动态代理来作为AOP的代理,这样任何接口都可以被代理.

<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
</dependency>
public interface Hello {
    String getHellow();
}
public class HelloImpl implements Hello{
    @Override
    public String getHellow() {
        return "Hello,spring AOP";
    }
}
public class MyBeforeAdvice {
    private static final Logger logger= LoggerFactory.getLogger(MyBeforeAdvice.class);

    //定义前置方法
    public void beforeMethod(){
        logger.info("this is a pig");
//        System.out.println("this is a before method.");
    }
}
       <bean id="hello" class="com.spring.aop.HelloImpl"/>
       <bean id="myBeforeAdvice" class="com.spring.aop.MyBeforeAdvice"/>
      <!--配置aop-->
       <aop:config>
           <aop:aspect id="before" ref="myBeforeAdvice">
               <aop:pointcut id="myPointCut" expression="execution(* com.spring.aop.*.*(..))"/>
               <aop:before method="beforeMethod" pointcut-ref="myPointCut"/>
           </aop:aspect>
       </aop:config>
public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
        Hello hello = context.getBean(Hello.class);
        System.out.println(hello.getHellow());
    }
}
上一篇 下一篇

猜你喜欢

热点阅读