使用注解方式实现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();
    }
}

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

  1. (转)使用Spring的注解方式实现AOP入门

    http://blog.csdn.net/yerenyuan_pku/article/details/52865330 首先在Eclipse中新建一个普通的Java Project,名称为spring ...

  2. 基于AspectJ的注解方式进行AOP开发

    -------------------siwuxie095                                     基于 AspectJ 的注解方式进行 AOP 开发         ...

  3. (转)使用Spring的注解方式实现AOP的细节

    http://blog.csdn.net/yerenyuan_pku/article/details/52879669 前面我们已经入门使用Spring的注解方式实现AOP了,现在我们再来学习使用Sp ...

  4. Spring系列之aAOP AOP是什么?+xml方式实现aop+注解方式实现aop

    Spring系列之aop aop是什么?+xml方式实现aop+注解方式实现aop 什么是AOP? AOP为Aspect Oriented Programming 的缩写,意识为面向切面的编程,是通过 ...

  5. spring----IOC注解方式以及AOP

    技术分析之Spring框架的IOC功能之注解的方式 Spring框架的IOC之注解方式的快速入门 1. 步骤一:导入注解开发所有需要的jar包 * 引入IOC容器必须的6个jar包 * 多引入一个:S ...

  6. Spring的注解方式实现AOP

    Spring对AOP的实现提供了很好的支持.下面我们就使用Spring的注解来完成AOP做一个例子. 首先,为了使用Spring的AOP注解功能,必须导入如下几个包.aspectjrt.jar,asp ...

  7. 使用Spring的注解方式实现AOP

    Spring对AOP的实现提供了很好的支持.下面我们就使用Spring的注解来完成AOP做一个例子. 首先,为了使用Spring的AOP注解功能,必须导入如下几个包.aspectjrt.jar,asp ...

  8. spring 纯注解方式 与AOP

    spring注解方式 以前我也使用过纯注解方式.现在在这里做个记录 我们先认识几个我们都耳熟能详的注解 @configuration :从spring3.0这个注解就可以用于定义配置类,可以替换xml ...

  9. 注解方式实现AOP编程

    步骤: 1) 先引入aop相关jar文件           (aspectj  aop优秀组件) spring-aop-3.2.5.RELEASE.jar   [spring3.2源码] aopal ...

随机推荐

  1. LeetCode 671. 二叉树中第二小的节点(Second Minimum Node In a Binary Tree) 9

    671. 二叉树中第二小的节点 671. Second Minimum Node In a Binary Tree 题目描述 给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 ...

  2. 【MIT 6.824 】分布式系统 课程笔记(一)

    Lecture 02 Infrastructure: RPC & threads 一.多线程挑战 共享数据: 使用互斥信号量.或者避免共享 线程间协作: 使用channels 或者 waitg ...

  3. HTML5从入门到精通(千锋教育)免费电子版+PDF下载

    本书是HTML5初学者极好的入门教材之一,内容通俗易懂.由浅入深.循序渐进.本书内容覆盖全面.讲解详细,其中包括标签语义化.标签使用规范.选择器类型.盒模型.标签分类.样式重置.CSS优化.Photo ...

  4. 通用32位CPU 常用寄存器及其作用

    目录 32位CPU所含有的寄存器 数据寄存器 变址寄存器 指针寄存器 段寄存器 指令指针寄存器 标志寄存器 32位CPU所含有的寄存器 4个数据寄存器(EAX.EBX.ECX和EDX) 2个变址和指针 ...

  5. Asp.net Identity 修改默认数据库,增加自定义字段

    visual studio 2013 先新建一个项目 选择MVC,确定 打开 Views\Shared\_Layout.cshtml文件,按自己的要求修改 改 <!DOCTYPE html> ...

  6. 关于Windows下的访问控制模型

    在探索Windows操作系统的过程中,发现很多有意思 的东西. Windows下的访问控制模型也是我在Github上浏览代码时,无意中发现的. 项目地址 https://github.com/Krut ...

  7. List、dictionary、hashtable、ArrayList集合

    集合的引用命名空间在 system.Collections下 1.为什么引入集合 因为数组长度是固定的,为了建立一个动态的"数组",所以引入了集合. 2.为什么引入ArrayLis ...

  8. linux环境weblogic的安装及新建域

    环境:inux 64位,jdk 64位,        jdk 安装用户应使用weblogic.若使用其他用户安装,须将jdk安装目录整体授权给wblogic用户 安装包:wls1036_dev.zi ...

  9. 如何导出robotframework的工程

    不知道是不是只有我一个小白,自己折腾了很久,也百度了很久,不知道怎么导出哇.现在来扫扫盲罗.我拿自己的项目举例:找到我的RF工程目录可以看到下面有3个项目,直接拷贝你想要的项目就ok啦,是不是so e ...

  10. ES6中 对字符串增强

    在曾经,我们只能用A.indexof(B)来判断A中是否含有B字符串: 现在在ES6中 有了: includes(), startswith(),endswith() reapt()重复次数: 输出 ...