_____________________________________________________________________________________
【ApplicationContext】通过实现ApplicationContextAware接口获取bean ssslinppp 2017-08-03 14:11 阅读:112 评论:0  
 
【Spring学习笔记-MVC-3.1】SpringMVC返回Json数据-方式1-扩展 ssslinppp 2015-07-25 10:58 阅读:14332 评论:0  
 
【Spring-AOP-学习笔记-6】@AfterThrowing增强处理简单示例 ssslinppp 2015-07-09 16:39 阅读:6067 评论:0  
 
【Spring-AOP-学习笔记-5】@AfterReturning增强处理简单示例 ssslinppp 2015-07-09 16:14 阅读:9487 评论:0  
 
【Spring-AOP-学习笔记-4】@After后向增强处理简单示例 ssslinppp 2015-07-09 15:58 阅读:730 评论:0  
 
【Spring学习笔记-MVC-17】Spring MVC之拦截器 ssslinppp 2015-07-01 15:03 阅读:222 评论:0  
 
【Spring学习笔记-MVC-1.0】Spring MVC架构介绍 ssslinppp 2015-07-01 10:21 阅读:185 评论:0  
 
【Spring学习笔记-MVC-16】Spring MVC之重定向-解决中文乱码 ssslinppp 2015-06-30 16:22 阅读:4464 评论:0  
 
【Spring学习笔记-MVC-15.1】Spring MVC之异常处理=404界面 ssslinppp 2015-06-30 12:20 阅读:155 评论:0  
 
【Spring学习笔记-MVC-15】Spring MVC之异常处理 ssslinppp 2015-06-30 12:13 阅读:1516 评论:0  
 
【Spring学习笔记-MVC-14】Spring MVC对静态资源的访问 ssslinppp 2015-06-29 16:15 阅读:183 评论:0  
 
【Spring学习笔记-MVC-13.2】Spring MVC之多文件上传 ssslinppp 2015-06-29 13:52 阅读:2895 评论:0  
 
【Spring学习笔记-MVC-13】Spring MVC之文件上传 ssslinppp 2015-06-29 11:11 阅读:5230 评论:1  
 
 
【Spring学习笔记-MVC-11--】Spring MVC之表单标签 ssslinppp 2015-06-26 15:27 阅读:156 评论:0  
 
【Spring学习笔记-MVC-10】Spring MVC之数据校验 ssslinppp 2015-06-26 11:29 阅读:383 评论:0  
 
 
【Spring学习笔记-MVC-8.1】SpringMVC之类型转换@initBinder ssslinppp 2015-06-25 10:55 阅读:582 评论:0  
 
【Spring学习笔记-MVC-8】SpringMVC之类型转换Converter ssslinppp 2015-06-24 16:51 阅读:14651 评论:3  
_____________________________________________________________________________________________
 
spring注解注入:<context:component-scan>详解
 
http://outofmemory.cn/java/spring/spring-DI-with-annotation-context-component-scan

spring从2.5版本开始支持注解注入,注解注入可以省去很多的xml配置工作。由于注解是写入java代码中的,所以注解注入会失去一定的灵活性,我们要根据需要来选择是否启用注解注入。

我们首先看一个注解注入的实际例子,然后再详细介绍context:component-scan的使用。

如果你已经在用spring mvc的注解配置,那么你一定已经在使用注解注入了,本文不会涉及到spring mvc,我们用一个简单的例子来说明问题。

本例中我们会定义如下类:

  1. PersonService类,给上层提供Person相关操作
  2. PersonDao类,给PersonService类提供DAO方法
  3. Person类,定义Person相关属性,是一个POJO
  4. App类,入口类,调用注解注入的PersonService类

PersonService类实现如下:

package cn.outofmemory.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class PersonService { @Autowired
private PersonDao personDao; public Person getPerson(int id) {
return personDao.selectPersonById(id);
}
}

在Service类上使用了@Service注解修饰,在它的私有字段PersonDao上面有@Autowired注解修饰。@Service告诉spring容器,这是一个Service类,默认情况会自动加载它到spring容器里。而@Autowired注解告诉spring,这个字段是需要自动注入的。

PersonDao类:

package cn.outofmemory.spring;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository; @Scope("singleton")
@Repository
public class PersonDao { public Person selectPersonById(int id) {
Person p = new Person();
p.setId(id);
p.setName("Person name");
return p;
}
}

在PersonDao类上面有两个注解,分别为@Scope和@Repository,前者指定此spring bean的scope是单例,你也可以根据需要将此bean指定为prototype,@Repository注解指定此类是一个容器类,是DA层类的实现。这个类我们只是简单的定义了一个selectPersonById方法,该方法的实现也是一个假的实现,只是声明了一个Person的新实例,然后设置了属性,返回他,在实际应用中DA层的类肯定是要从数据库或者其他存储中取数据的。

Person类:

package cn.outofmemory.spring;

public class Person {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Person类是一个POJO。

App类:

package cn.outofmemory.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Hello spring! from outofmemory.cn
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml");
        PersonService service = appContext.getBean(PersonService.class);
        Person p = service.getPerson(1);
        System.out.println(p.getName());
    }
}

在App类的main方法中,我们初始化了ApplicationContext,然后从中得到我们注解注入的PersonService类,然后调用此对象的getPerson方法,并输出返回结果的name属性。

注解注入也必须在spring的配置文件中做配置,我们看下spring.xml文件的内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false">
<context:include-filter type="regex" expression="cn\.outofmemory\.spring\.[^.]+(Dao|Service)"/>
</context:component-scan>
</beans>

这个配置文件中必须声明xmlns:context 这个xml命名空间,在schemaLocation中需要指定schema:

           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd

这个文件中beans根节点下只有一个context:component-scan节点,此节点有两个属性base-package属性告诉spring要扫描的包,use-default-filters="false"表示不要使用默认的过滤器,此处的默认过滤器,会扫描包含Service,Component,Repository,Controller注解修饰的类,而此处我们处于示例的目的,故意将use-default-filters属性设置成了false。

context:component-scan节点允许有两个子节点<context:include-filter>和<context:exclude-filter>。filter标签的type和表达式说明如下:

Filter Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example..*Service+ AspectJ語法
regex org\.example\.Default.* Regelar Expression
custom org.example.MyTypeFilter Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter

在我们的示例中,将filter的type设置成了正则表达式,regex,注意在正则里面.表示所有字符,而\.才表示真正的.字符。我们的正则表示以Dao或者Service结束的类。

我们也可以使用annotaion来限定,如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> 
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> 
</context:component-scan>
</beans>

这里我们指定的include-filter的type是annotation,expression则是注解类的全名。

另外context:conponent-scan节点还有<context:exclude-filter>可以用来指定要排除的类,其用法和include-filter一致。

最后我们要看下输出的结果了,运行App类,输出:

2014-5-18 21:14:18 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1cac6db: startup date [Sun May 18 21:14:18 CST 2014]; root of context hierarchy
2014-5-18 21:14:18 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring.xml]
2014-5-18 21:14:18 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1fcf790: defining beans [personDao,personService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor]; root of factory hierarchy
Person name

前几行都是spring输出的一些调试信息,最后一行是我们自己程序的输出。

本文源码下载:spring-DI-annotation.zip

 
_____________________________________________________________________________________________
 

项目结构


 
 

业务代码


@Component("hello")
public class HelloImpl implements Hello
{
    // 定义一个简单方法,模拟应用中的业务逻辑方法
    public void foo()
    {
        System.out.println("执行Hello组件的foo()方法");
    }
    // 定义一个addUser()方法,模拟应用中的添加用户的方法
    public int addUser(String name , String pass)
    {
        System.out.println("执行Hello组件的addUser添加用户:" + name);
        return 20;
    }

}  


@Component("world")
public class WorldImpl implements World
{
    // 定义一个简单方法,模拟应用中的业务逻辑方法
    public void bar()
    {
        System.out.println("执行World组件的bar()方法");
    }
}

定义切面Bean


@Aspect
public class LogAspect
{
    // 匹配org.crazyit.app.service.impl包下所有类的、
    // 所有方法的执行作为切入点
    @AfterReturning(returning="rvt"
        , pointcut="execution(* org.crazyit.app.service.impl.*.*(..))")
    // 声明rvt时指定的类型会限制目标方法必须返回指定类型的值或没有返回值
    // 此处将rvt的类型声明为Object,意味着对目标方法的返回值不加限制
    public void log(Object rvt)
    {
        System.out.println("获取目标方法返回值:" + rvt);
        System.out.println("模拟记录日志功能...");
    }

}  


说明:returing属性所指定的形参名必须对应增强处理中的一个形参名,当目标方法执行返回后,返回值作为相应的参数值传入增强处理方法中。
虽然AfterReturning增强处理可以访问到目标方法的返回值,但它不可以改变目标方法的返回值。

配置文件


<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <!-- 指定自动搜索Bean组件、自动搜索切面类 -->
    <context:component-scan base-package="org.crazyit.app.service
        ,org.crazyit.app.aspect">
        <context:include-filter type="annotation"
            expression="org.aspectj.lang.annotation.Aspect"/>
    </context:component-scan>
    <!-- 启动@AspectJ支持 -->
    <aop:aspectj-autoproxy/>

</beans>

测试代码


public class BeanTest
{
    public static void main(String[] args)
    {
        // 创建Spring容器
        ApplicationContext ctx = new
            ClassPathXmlApplicationContext("beans.xml");
        Hello hello = ctx.getBean("hello" , Hello.class);
        hello.foo();
        hello.addUser("孙悟空" , "7788");
        World world = ctx.getBean("world" , World.class);
        world.bar();
 
    }

}


 

链接:
《@AfterThrowing增强处理简单示例》http://www.cnblogs.com/ssslinppp/p/4633595.html 
《@AfterReturning增强处理简单示例》http://www.cnblogs.com/ssslinppp/p/4633496.html 
《@After后向增强处理简单示例》http://www.cnblogs.com/ssslinppp/p/4633427.html 
《@Before前向增强处理简单示例》 http://www.cnblogs.com/ssslinppp/default.html?page=7 

【Spring-AOP-学习笔记】的更多相关文章

  1. Spring AOP学习笔记01:AOP概述

    1. AOP概述 软件开发一直在寻求更加高效.更易维护甚至更易扩展的方式.为了提高开发效率,我们对开发使用的语言进行抽象,走过了从汇编时代到现在各种高级语言繁盛之时期:为了便于维护和扩展,我们对某些相 ...

  2. Spring AOP学习笔记02:如何开启AOP

    上文简要总结了一些AOP的基本概念,并在此基础上叙述了Spring AOP的基本原理,并且辅以一个简单例子帮助理解.从本文开始,我们要开始深入到源码层面来一探Spring AOP魔法的原理了. 要使用 ...

  3. Spring AOP学习笔记03:AOP的核心实现之获取增强器

    上文讲了spring是如何开启AOP的,简单点说就是将AnnotationAwareAspectJAutoProxyCreator这个类注册到容器中,因为这个类最终实现了BeanPostProcess ...

  4. Spring AOP学习笔记05:AOP失效的罪因

    前面的文章中我们介绍了Spring AOP的简单使用,并从源码的角度学习了其底层的实现原理,有了这些基础之后,本文来讨论一下Spring AOP失效的问题,这个问题可能我们在平时工作中或多或少也会碰到 ...

  5. Spring AOP学习笔记

      Spring提供了一站式解决方案:          1) Spring Core  spring的核心功能: IOC容器, 解决对象创建及依赖关系          2) Spring Web ...

  6. Spring AOP学习笔记(1)-概念

    1.Aspect 横切在多个类的一个关注点,在Spring AOP中,aspect实现是一个规则的类或@Aspect标注的规则类.例如:事务管理 2.Join point 程序执行过程中的一个点,例如 ...

  7. Spring AOP学习笔记04:AOP核心实现之创建代理

    上文中,我们分析了对所有增强器的获取以及获取匹配的增强器,在本文中我们就来分析一下Spring AOP中另一部分核心逻辑--代理的创建.这部分逻辑的入口是在wrapIfNecessary()方法中紧接 ...

  8. Spring入门IOC和AOP学习笔记

    Spring入门IOC和AOP学习笔记 概述 Spring框架的核心有两个: Spring容器作为超级大工厂,负责管理.创建所有的Java对象,这些Java对象被称为Bean. Spring容器管理容 ...

  9. 【转】Spring.NET学习笔记——目录

    目录 前言 Spring.NET学习笔记——前言 第一阶段:控制反转与依赖注入IoC&DI Spring.NET学习笔记1——控制反转(基础篇) Level 200 Spring.NET学习笔 ...

  10. Spring MVC 学习笔记12 —— SpringMVC+Hibernate开发(1)依赖包搭建

    Spring MVC 学习笔记12 -- SpringMVC+Hibernate开发(1)依赖包搭建 用Hibernate帮助建立SpringMVC与数据库之间的联系,通过配置DAO层,Service ...

随机推荐

  1. [BUAA软工]Alpha阶段项目展示

    [冰多多]Alpha项目展示 冰多多项目: 语音coding 助手, alpha阶段目标: 语音辅助输入 一. 团队成员的简介和个人博客地址 成员 角色 个人博客地址 卓培锦 PM, 后端开发 htt ...

  2. Leetcode: 43. 接雨水

    题目描述: 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水. 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情 ...

  3. Oracle数据库备份、灾备的23个常见问题

    为了最大限度保障数据的安全性,同时能在不可预计灾难的情况下保证数据的快速恢复,需要根据数据的类型和重要程度制定相应的备份和恢复方案.在这个过程中,DBA的职责就是要保证数据库(其它数据由其它岗位负责) ...

  4. [linux]测硬盘读写速度、内存读写速度

    测硬盘的读写速度可以用以下命令:dd if=/dev/zero of=file bs=1M count=1024 测内存读写速度可以使用以下命令: dd if=/dev/zero of=/dev/nu ...

  5. Android Studio 3.4 修改 .android 和.gradle缺省目录-windows7x64专业版环境。

    说明:缺省会在用户目录建立.android和.gradle目录.会挤满C盘.可以改变缺省目录. 改变.gradle目录路径示例,修改到D:\android目录,步骤: 1.建立d:\android目录 ...

  6. Feign进行文件上传+表单调用

    Feigin默认是不支持文件上传和表单提交的,需要做一些配置才能支持. 1.feign依赖 图中红色为form支持必须的jar. 2.添加自定义Encoder类: import static java ...

  7. 配置HTTPS全过程

    HTTPS配置全过程服务器配置https协议HTTPS,是以安全为目标的HTTP通道,简单讲是HTTP的安全版.即HTTP下加入SSL层,HTTPS的安全基础是SSL,因此加密的详细内容就需要SSL. ...

  8. centos6.9安装python3.6.9独立的virtualenv环境,并且能正确引入ssl

    centos6.9安装python3.6.9独立的virtualenv环境,并且能正确引入ssl 1.编译安装python3.6环境# 安装依赖yum -y install zlib-devel bz ...

  9. VMware设置桥接模式(使虚拟机拥有独立IP访问外网)

    1.关闭虚拟机里的系统 2.VMware主窗口 编辑---->虚拟网络编辑器 右下角----> 更改设置---->出现  桥接模式 桥接到:看本机所连接的网络, 网络属性中有一项“描 ...

  10. DL Practice:Cifar 10分类

    Step 1:数据加载和处理 一般使用深度学习框架会经过下面几个流程: 模型定义(包括损失函数的选择)——>数据处理和加载——>训练(可能包括训练过程可视化)——>测试 所以自己写代 ...