使用注解方式实现 AOP和IoC

使用注解方式实现AOP和IoC

IOC和DI的注解

IOC:

@Component:实现Bean组件的定义

@Repository:用于标注DAO类,功能与@Component作用相当

@Service:用于标注业务类

@Controller:用于标注控制器

DI:

@Resource(name="userService")

默认ByName方式,如果name确实默认按照ByType方式注入

@Autowired

默认ByType方式,如果出现同名类,则不能按照Type进行注入

需要使用@Qualifier 指明ID

1.  使用注解实现IoC案例

1.1 编写applicationContext.xm文件
<!--扫描注解:包扫描器-->
<context:component-scan base-package="cn.spring"/>
1.2创建mapper接口
public interface UserMapper {
    public int addUser(User user);
}
1.3 创建mapper接口实现类
@Repository
public class UserMapperImpl implements UserMapper {

    @Override
    public int addUser(User user) {
        System.out.println("添加成功");
        return 1;
    }
}
1.4创建Service接口
public interface UserService {
    public int addUser(User user);
}
1.5创建Service接口实现类
@Service("userServiceImpl")
public class UserServiceImpl implements UserService {
    //植入Dao层对象
    //@Resource默认是根据byName的方式,但是一旦名字为空 ,就根据byType
    @Autowired
    private UserMapper userMapper;
    @Override
    public int addUser(User user) {

        return userMapper.addUser(user);
    }

}
1.6 编写测试类
@org.junit.Test
public void test2() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //通过类型调度
    //UserInfoService userService=context.getBean(UserService.class);
    //指定@Service的value值后使用bean的id名称调度
    UserService userServiceImpl = (UserService) context.getBean("userServiceImpl");
    userServiceImpl.addUser(new User());
}
1.7 控制台

使用注解方式实现AOP

  • 实现AOP的注解有
  • @Aspect 声明切面
  • @Ponitcut 声明公共的切点表达式
  • @Before 前置增强
  • @AfterReturning 后置增强
  • @Around 环绕增强
  • @AfterThrowing 异常抛出增强
  • @After 最终增强

  1.使用注解方式实现前置增强和后置增强

    1.1  编写applicationContext.xml文件

<!--开启AOP注解支持-->
<aop:aspectj-autoproxy/>

    1.2 创建Service类

@Service("IDoSomeService")
public class IDoSomeService {

    public void doSome(){
        System.out.println("业务类中dosome方法");
    }

    public void say(){
        System.out.println("业务类中say方法");
    }
}

    1.3 编写切面类实现增强

@Aspect
@Component
public class MyAdvice {

@Pointcut("execution(* *..service.*.*(..))")
public void point(){

}

    @Before("point()")
    public void before(){
        System.out.println("前置增强");
    }

    @AfterReturning("execution(* *..service.*.*(..))")
    public void afterReturning(){
        System.out.println("后置增强");
    }

}

    1.4 编写测试类

@org.junit.Test
public void test3(){
    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    IDoSomeService iDoSomeService = (IDoSomeService)context.getBean("IDoSomeService");
    iDoSomeService.doSome();
    iDoSomeService.say();
}

    1.5 控制台

 

  2. 使用注解方式实现环绕增强

    2.1  编写applicationContext.xml文件

<!--扫描注解:包扫描器-->
<context:component-scan base-package="cn.spring"/>

<!--开启AOP注解支持-->
<aop:aspectj-autoproxy/>

    2.2 创建Service类

@Service("IDoSomeService")
public class IDoSomeService {

    public void doSome(){
        System.out.println("业务类中dosome方法");
    }

    public void say(){
        System.out.println("业务类中say方法");
    }
}

    2.3编写切面类实现增强

@Aspect
@Component
public class AroundAdvisor {

    @Around("execution(* *..service.*.*(..))")
    public void around(ProceedingJoinPoint PJ) throws Throwable {
        System.out.println("环绕增强");
        PJ.proceed();
        System.out.println("环绕增强");
    }
}

    2.4编写测试类

@org.junit.Test
public void test3(){
    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    IDoSomeService iDoSomeService = (IDoSomeService)context.getBean("IDoSomeService");
    iDoSomeService.doSome();
    iDoSomeService.say();
}

    2.5控制台

3. 使用注解实现异常抛出增强

在exception包下完成对应的用例。

声明切面类

@Aspect
public class AroundLoggerAnno {
   @Around("execution(* com.cmy.service.*.*(..))")
   public Object aroundLogger(ProceedingJoinPoint jp) throws Throwable {
      System.out.println("调用 " + jp.getTarget() + " 的 " + jp.getSignature().getName()
            + " 方法。方法入参:" + Arrays.toString(jp.getArgs()));
      try {
         Object result = jp.proceed();
         System.out.println("调用 " + jp.getTarget() + " 的 "
               + jp.getSignature().getName() + " 方法。方法返回值:" + result);
         return result;
      } catch (Throwable e) {
         System.out.println(jp.getSignature().getName() + " 方法发生异常:" + e);
         throw e;
      } finally {
         System.out.println(jp.getSignature().getName() + " 方法结束执行。");
      }
   }

创建Spring的核心配置文件,开启Spring对IOC和AOP注解的支持

新增app-08.xml文件

<!--开启Spring IOC的注解支持 base-package 包扫描语句 com.cmy包下的注解-->
<context:component-scan base-package="com.cmy"/>
<!--配置增强类 交给Spring容器管理-->
<bean class="com.cmy.exception.ErrorLogger"></bean>
<!--开启Spring AOP注解的支持-->
<aop:aspectj-autoproxy />

编写测试用例,在DoSomeServiceImpl模拟异常

public class Demo2 {
    public static void main(String[] args) {
        //声明式增强 必须加载Spring容器
        ApplicationContext app = new ClassPathXmlApplicationContext("com/cmy/exception/app-08.xml");
        //获取代理对象
        DoSomeService doSomeService=(DoSomeService)app.getBean("doSomeService");
        doSomeService.say();
    }
}

  

4.使用注解实现最终增强

使用After包,增加切面类

/**
 * 通过注解实现最终增强
 */
@Aspect
public class AfterLoggerAnno {

   @After("execution(* com.cmy.service.*.*(..))")
   public void afterLogger(JoinPoint jp) {
      System.out.println(jp.getSignature().getName() + " 方法结束执行。");
   }
}

新建app-10.xml文件

<!--开启Spring IOC的注解支持 base-package 包扫描语句 com.cmy包下的注解-->
<context:component-scan base-package="com.cmy"></context:component-scan>
<!--配置增强类 交给Spring容器管理-->
<bean class="com.cmy.after.AfterLoggerAnno"></bean>
<!--开启Spring AOP注解的支持-->
<aop:aspectj-autoproxy />

创建测试用例

public class Demo2 {
    public static void main(String[] args) {
        //声明式增强 必须加载Spring容器
        ApplicationContext app = new ClassPathXmlApplicationContext("com/cmy/after/app-10.xml");
        //获取代理对象
        DoSomeService doSomeService=(DoSomeService)app.getBean("doSomeService");
        doSomeService.say();
    }
}

原文地址:https://www.cnblogs.com/1314Justin/p/11776704.html

时间: 2024-08-02 03:20:33

使用注解方式实现 AOP和IoC的相关文章

使用Spring的注解方式实现AOP入门

首先在Eclipse中新建一个普通的Java Project,名称为springAOP.为了使用Spring的注解方式进行面向切面编程,需要在springAOP项目中加入与AOP相关的jar包,spring aop需要额外的jar包有: com.springsource.org.aopalliance-1.0.0.jar com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar spring-aop-4.2.5.RELEASE.jar sprin

使用Spring的注解方式实现AOP的细节

前面我们已经入门使用Spring的注解方式实现AOP了,现在我们再来学习使用Spring的注解方式实现AOP的一些细节.本文是建立在使用Spring的注解方式实现AOP入门的案例的基础之上的. 本文是来讲解使用Spring的注解方式实现AOP的一些细节,其实说白了就是学习如何使用各种通知而已,例如前置通知.后置通知.异常通知.最终通知.环绕通知等,之前我们已经学习了前置通知,现在就来学习剩余的通知. 我们先来看后置通知,此时须将MyInterceptor类的代码修改为: /** * 切面 * @

Spring之AOP基本概念及通过注解方式配置AOP

为什么使用AOP 传统方法 AOP前前奏 首先考虑一个问题,假设我们要设计一个计算器,有如下两个需求: - 在程序运行期间追踪正在放生的活动 - 希望计算器只能处理正数的运算 通常我们会用如下代码进行实现: 定义一个接口: public interface ArithmeticCalculator { int add(int i, int j); int sub(int i, int j); int mul(int i, int j); int div(int i, int j); } 实现类(

spring注解方式实现DI和IOC

注解复习: 1.注解就是为了说明java中的某一个部分的作用(Type) 2.注解都可以用于哪个部门是@Target注解起的作用 3.注解可以标注在ElementType枚举类所指定的位置上 4. 元注解 @Documented    //该注解是否出现在帮助文档中 @Retention(RetentionPolicy.RUNTIME) //该注解在java,class和运行时都起作用 @Target(ElementType.ANNOTATION_TYPE)//该注解只能用于注解上 public

Spring的注解方式实现AOP

Spring对AOP的实现提供了很好的支持.下面我们就使用Spring的注解来完成AOP做一个例子. 首先,为了使用Spring的AOP注解功能,必须导入如下几个包.aspectjrt.jar,aspectjweaver.jar,cglib-nodep.jar. 然后我们写一个接口 [java] view plain copy print? package com.bird.service; public interface PersonServer { public void save(Str

Spring笔记(五)--注解方式实现AOP

包:aspectjrt.jar.aspectjweaver.jar AOP:面向切面的编程 1.XML配置: 2.注解. 一.注解方式: 打开注解处理器: <aop:aspectj-autoproxy/> 接口: 1 package com.dwr.spring.proxy; 2 3 public interface UserManager { 4 public void addUser(String username,String password); 5 public void delet

Spring源码窥探之:注解方式的AOP原理

AOP入口代码分析 通过注解的方式来实现AOP1. @EnableAspectJAutoProxy通过@Import注解向容器中注入了AspectJAutoProxyRegistrar这个类,而它在容器中的名字是org.springframework.aop.config.internalAutoProxyCreator.2. AspectJAutoProxyRegistrar实现了ImportBeanDefinitionRegistrar接口,所以可以向容器中注册Bean的定义信息.3. 通过

AspectJ的注解方式实现AOP

1.引入spring基础包2.引入aspectJ的jar包: com.springsource.org.aopalliance-*.jar com.springsource.org.aspectj.weaver-*.jar 3.spring.xml加入相关配置 <!-- 设置使用注解的类所在的包 --> <context:component-scan base-package="net.shibit.*"/> <!-- 使AspectJ注解起作用:自动为匹

spring注解方式配置AOP

applicationContext.xml里添加: <aop:aspectj-autoproxy/>