Spring的Annotation配置方法

本文详细介绍了如何使用Spring注解简化bean配置的过程,包括引入命名空间、启用注解支持及扫描包路径等步骤,并对比了@Resource与@Autowired的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=small]手动配置Spring的bean是一件极为头疼的事情,工作量大不说,还特别容易写错,Annotation标签很好的解决了这个问题,会帮我们剩下很多时间,接下来就是配置的方法:[/size]

第一步:添加common-annotations.jar包;
第二步:引入对应的命名空间及对应的Schema文件地址:
<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">

第三步:在配置文件中添加<context:annotation-config /> 让Spring启用对annotation的支持。它其实是注册了多个对annotation进行解析处理的处理器:
[list]
[*]AutowiredAnnotionBeanPostProcessor
[*]CommonAnnotationBeanPostProcessor
[*]PersistenceAnnotionBeanPostProcessor
[*]RequiredAnnotationBeanPostProcessor.
[/list]
第四步:在配置文件中添加需要进行扫描的包路径,例如:<context:component-scan base-package="com.mossad" />就是扫描com.mossad包及其子包下所有的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">

<!-- 扫描标记了注解的类 -->
<context:annotation-config />
<context:component-scan base-package="com.mossad" />

</beans>

大功告成!接下来就可以使用各种标签进行各种配置了!
:D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D
记一下@Resource标签和@Autowired标签的区别和用法:
1、@Resource和@Autowired都可以用来标记bean的field属性、成员方法、构造函数、形参的,标记field属性的目的是为field注入相应的bean。
2、@Resource标签默认是byName自动注入,也就是说它会自动注入与field名称相同的bean
	@Resource
private StockService stockService;
也可以通过设置name属性来指定注入bean的名称,如下所示,此时注入的bean就是abcService而不是stockService了
	@Resource("abcService")
private StockService stockService;
它还有一个属性是type,用来指定bean的类型,如果不设置,那么Spring会通过反射获取field的类型,然后查找相同类型的bean进行注入,如果多余一个则会抛出异常。
3、@Autowired标签默认是byType自动注入,但是它也可以通过另外一个@Qualifier标签指定bean的name
	@Autowired
@Qualifier("stockService")
private StockService stockService;

4、@Resource位于javax.annotation包下,是来自Java EE规范的一个Annotation,Spring直接借鉴了该Annotation来为目标Bean指定协作者Bean;@Autowired是Spring自己的标签,来提供自动装配。
5、设置了这两个标签之后,就都不需要setter方法了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值