定义Bean注解
| 注解 | 描述 |
|---|---|
| @Component | 定义Spring中的Bean,可以表示任何层的Bean(Controller、Service、dao),这是一个泛化的注解。 |
| @Repository | 功能与Compenent完全一样,用于注解Repository层(数据访问层DAO层)的Bean |
| @Service | 功能与Compenent完全一样,用于注解Service层的Bean |
| @Controller | 功能与Compenent完全一样,用于注解Controller层的Bean |
装配Bean注解
| 注解 | 描述 |
|---|---|
| @Autowired | 用于装配Bean的属性。可标注在成员变量、成员变量的setter方法、构造函数上。@Autowired默认按照Bean的类型进行装配。若有多个相同类型的Bean实例,将抛出BeanCreationException。 |
| @Resource | 与@Autowired功能相同,不同的是@Resource默认按照Bean的名称进行装配。 |
| @Qualifier | 与@Autowired注解配合使用,会默认的按Bean类型装配修改为按Bean的实例名称装配。Bean的实例名称由@Qualifier注解参数决定。 |
@Resource 中有两个重要属性:name 和 type。
- name用于指定装配Bean的实例名称,type用于指定装配Bean的类型。
- 如果指定 name 属性,则按实例名称进行装配;如果指定 type 属性,则按 Bean 类型进行装配。
- 如果都不指定,则先按 Bean 实例名称装配,如果不能匹配,则再按照 Bean 类型进行装配;如果都无法匹配,则抛出 NoSuchBeanDefinitionException 异常。
xml
<?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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="cn.lingyiwin.annotation"/>
</beans>
本文详细介绍了Spring框架中用于定义和装配Bean的注解,包括@Component、@Repository、@Service和@Controller,它们分别用于标记不同层的Bean。同时,还讲解了@Autowired、@Resource和@Qualifier注解在装配Bean过程中的作用和区别,以及如何通过XML配置启用组件扫描。
446

被折叠的 条评论
为什么被折叠?



