`
m635674608
  • 浏览: 4939935 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

spring注解注入:<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;@ServicepublicclassPersonService{@AutowiredprivatePersonDao personDao;publicPerson 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")@RepositorypublicclassPersonDao{publicPerson selectPersonById(int id){Person p =newPerson();
		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;publicclassPerson{privateint id;privateString name;publicint getId(){return id;}publicvoid setId(int id){this.id = id;}publicString getName(){return name;}publicvoid 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
 *
 */publicclassApp 
{
    publicstaticvoid main(String[] args )
    {
        ApplicationContext appContext =newClassPathXmlApplicationContext("/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"?><beansxmlns="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-scanbase-package="cn.outofmemory.spring"use-default-filters="false"><context:include-filtertype="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"?><beansxmlns="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-scanbase-package="cn.outofmemory.spring"use-default-filters="false"><context:include-filtertype="annotation"expression="org.springframework.stereotype.Repository"/> 
		<context:include-filtertype="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-1821:14:18 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息:Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1cac6db: startup date [SunMay1821:14:18 CST 2014]; root of context hierarchy
2014-5-1821:14:18 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息:Loading XML bean definitions fromclass path resource [spring.xml]2014-5-1821: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扫描器—spring组件扫描使用详解

    NULL 博文链接:https://gaozzsoft.iteye.com/blog/1523898

    spring-context-support-1.0.10-API文档-中文版.zip

    赠送jar包:spring-context-support-1.0.10.jar; 赠送原API文档:spring-context-support-1.0.10-javadoc.jar; 赠送源代码:spring-context-support-1.0.10-sources.jar; 赠送Maven依赖信息文件:spring-context-...

    Spring注释 注入方式源码示例,Annotation

    &lt;context:component-scan base-package="Mode"&gt;&lt;/context:component-scan&gt; //表示在包mode下面的类将扫描带有@Component,@Controller,@Service,@Repository标识符的类并为之注入对象。 据说是因为XML配置太烦锁而...

    Spring 报错:元素 "context:component-scan" 的前缀 "context" 未绑定的问题解决

    主要介绍了Spring 报错:元素 "context:component-scan" 的前缀 "context" 未绑定的问题解决的相关资料,需要的朋友可以参考下

    logback-ext-spring

    spring使用logback的扩展,使用起来非常方便。在web.xml中配置: ... &lt;listener-class&gt;ch.qos.logback.ext.spring.web.LogbackConfigListener&lt;/listener-class&gt; &lt;/listener&gt; 即可加载logback配置,使用logback。

    springweb3.0MVC注解(附实例)

    &lt;context:component-scan base-package="com.baobaotao.web"/&gt; &lt;!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 --&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation. ...

    spring和hibernate整合

    在web.Xml中&lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; ... &lt;listener-class&gt;org.springframework.web.context.request.RequestContextListener&lt;/listener-class&gt; &lt;/listener&gt;

    spring配置中<context-param> 和<init-param>的 区别

    &lt;context-param&gt; 和&lt;init-param&gt;的 区别代码 博文链接:https://xhy0422.iteye.com/blog/46319

    基于java的企业级应用开发:Spring MVC的核心类和注解.ppt

    在使用时,只需将其配置在项目的web.xml文件中,其配置代码如下: &lt;servlet&gt; &lt;servlet-name&gt;springmvc&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;init-...

    Spring MVC 框架应用实例

    &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/database.xml /WEB-INF/applicationContext.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-...

    xfire的使用详解

    &lt;param-value&gt;classpath:spring/app.xml,classpath:org/codehaus/xfire/spring/xfire.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;!--配置xfire ws--&gt; &lt;servlet&gt; &lt;servlet-name&gt;XFireServlet&lt;/servlet-name&gt; ...

    springboot 基础简易实例, maven项目

    &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.1.4.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;com.example&lt;/groupId&gt; &lt;artifactId&gt;...

    基于java的企业级应用开发:Spring的核心容器.ppt

    spring/applicationContext.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt; org.springframework.web.context.ContextLoaderListener &lt;/listener-class&gt; &lt;/listener&gt; ApplicationContext * * * *...

    简单spring MVC 配置

    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;servlet&gt; &lt;servlet-name&gt;test&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet....

    生活轨迹SSH服务端

    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;!-- 默认找的文件名 --&gt; &lt;/listener&gt; &lt;!-- Context Configuration locations for Spring XML files --&gt; &lt;context...

    ssh框架的搭建

    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- Listener log4jConfigLocation --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web....

    cas 配置client 1.0 &2.0 及proxy DEMO 说明

    &lt;description&gt;cas1 demo&lt;/description&gt; &lt;!-- cas filter --&gt; &lt;filter&gt; &lt;filter-name&gt;CAS Filter&lt;/filter-name&gt; &lt;filter-class&gt; edu.yale.its.tp.cas.client.filter.CASFilter &lt;/filter-class&gt; &lt;!-- ...

Global site tag (gtag.js) - Google Analytics