Spring学习笔记(4)---基于注解的配置

本文介绍了如何使用Spring注解进行依赖注入及组件扫描配置。详细解释了@Autowired与@Resource的区别,并展示了如何通过XML配置启用注解支持,实现无XML的零配置。

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

要使注解可用,必须使用 Java 5 (Tiger)或更新的版本,以使得可以访问源代码层次的注解。这些注解可以被注册为独立 bean 的定义,但它们也可以被隐式地注册,通过基于 XML 的配置方式,如下例(请注意包含 'context' 命名空间):
[color=red]也就是说要使用Spring的注解,就必须使用如下的配置:
[/color]
<?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/>

</beans>

这个配置隐式注册了多个对注解解析处理的处理器
[b]1.@Autowired和@Resource[/b]
这两个注解的区别是:
@Autowired默认按照类型装配,后者按照名称装配,找不到再按照类型。
推荐使用@Resource
 @Resource
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}


[b]2.对受管组件的Classpath扫描实现零配置(没有bean配置)
[/b]
必须有如下配置:
<?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:component-scan base-package="org.example"/>

</beans>

base-package="org.example"这里写上需要扫描的类包,扫描标注了有@Repository, @Component、@Service和 @Controller的注解的类,有的话,就会把标注了这些注解的类交给Spring管理,从而不用再去XML里配置相关的bean。
例如:
@Service
public class SimpleMovieLister {

private MovieFinder movieFinder;

@Autowired
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}


@Service用于标注业务组件,@Controller用于标注控制层组件,@Repository用于标注DAO组件,@Component泛指组件,用于不好归类的情况。

就目前Spring2.5的版本来说,这四个注解,作用一样。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值