spring2.5中基于注释的配置方式浅析

spring2中基于注释的配置方式浅析

<script type="text/javascript"></script> 注: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.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" 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相似。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值