码迷,mamicode.com
首页 > 编程语言 > 详细

Spring杂谈

时间:2015-02-11 23:07:03      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:

学习Spring了一段时间,发现东西有很多,而且看完很容易忘记,故在此逐一列出。

1.注解

@Autowired 自动装配

@Qualifier 指定装配的类型,将注入策略从byType改为了byName。例如:@Autowired @Qualifier("beanid")

@Autowired起作用必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

同时需要指定命名空间

<beans  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 

JSR-250

@Resource

@Resource的作用相当于@Autowired,只不过@Autowired按 byType 自动注入,而@Resource默认按 byName 自动注入罢了。

@PostConstruct 和 @PreDestroy

@PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。可同时指定多个方法。

要让 JSR-250 的注释生效,还需要在 Spring 容器中注册一个负责处理这些注释的 BeanPostProcessor

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>

 

<context:annotationconfig/> 将隐式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessorPersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor 这 4 个 BeanPostProcessor

 

在配置文件中使用 context 命名空间之前,必须在 <beans> 元素中声明 context 命名空间。

<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-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 

 @Component

在使用 @Component注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。

<context:component-scan base-package="com.baobaotao"> <context:include-filter type="regex" expression="com\.baobaotao\.service\..*"/> <context:exclude-filter type="aspectj" expression="com.baobaotao.util..*"/> </context:component-scan>
<context:component-scan/> 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能
(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor),因此当使用 <context:component-scan/> 后,
就可以将 <context:annotation-config/> 移除了。

默认情况下通过 @Component定义的 Bean 都是 singleton 的,如果需要使用其它作用范围的Bean,可以通过@Scope注释来达到目标

 

@Controller  @Service  @Repository 同 @Component

 

<mvc:annotation-driven/>
相当于注册了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean,配置一些messageconverter。即解决了@Controller注解的使用前提配置。

 

Spring杂谈

标签:

原文地址:http://www.cnblogs.com/focusahaha/p/4287056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!