注:annotation-based configuration是一把双刃剑,与xml-based configuration相比,有利有弊,其中利弊不在本文讨论的范围内,不再多说,仅提醒各位根据自身的需要谨慎选择。
使用Annotaion似乎成了时尚和趋势,spring2.5提供了一些Annotation,使开发者可以简化我们的配置文件。本文简单阐述一下spring2.5中的Annotation是如何使用的,不做深层次的研究。 一、配置文件可以简化到什么程度? 使用annotation以前,我们要在xml配置文件中配置每一个我们用spring管理的bean,有十个要写十个,有一百个要写一百个...... 使用annotation之后,及至情况下,我们可以一个都bean都不写,那么我们的配置文件就要写成下面的样子: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www./schema/beans" xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:context="http://www./schema/context" xsi:schemaLocation="http://www./schema/beans [url]http://www./schema/beans/spring-beans-2.5.xsd[/url] [url]http://www./schema/context[/url] [url]http://www./schema/context/spring-context-2.5.xsd[/url]" default-autowire="byName" default-lazy-init="true"> <context:annotation-config /> <context:component-scan base-package="org.example"> <context:include-filter type="regex" expression=".*Stub.*Repository"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan> </beans> 看看,上面没有一个<bean>标签吧!下面简单解释一下下面的配置: 1) <beans>标签里面,以前我们用DTD,现在我们用的是XMLSchema-style,具体含义本文不讲了(本文是“浅析”教程嘛) 2) <context:annotation-config />表示,我们要使用Annotation-based的bean管理方式。 3) <context:component-scan base-package="org.example">表示org.example包下的一些类使用Annotation-based的bean管理方式,换句话说就是在这个包下的Annotation才会起作用,其他包下的没用。 4) <context:include-filter和<context:exclude-filter就是用正则表达式来include和exclude指定包(就是org.example)想的一下bean。 二、怎么什么声明一个spring管理的bean?怎么注入bean? 声明:在bean上加注释@Component,例: package org.example; @Component("sampleBean") public class SampleBean{ //...... } 注入:在field,seter等上加注释@Autowired,例: package org.example; public class SampleBeanInjection{ private SampleBean sampleBean; @Autowired public setSampleBean(SampleBean sampleBean){ //...... } //...... } 如上的例子不是很恰当,明眼人见谅。 三、有哪些Annotation可用? 在org.springframework.stereotype包下,有用于声明bean的Annotation: Component Controller Repository Service 在org.springframework.beans.factory.annotation包下,有用于注入bean的Annotation: Autowired Qualifier Required 在JSR-250的规范中(即j2ee的javax.annotation包下),有@Resource用来注入bean,其功能与@Autowired相似。 |
|