Spring註解

一.裝配bean基於註解

1. @Component

@component(代替的是<bean class="..."/>)
@component("person")(代替的是<bean id="person" class="..."/>)

2.web開發,提供3個@Component註解衍生註解(功能一樣)

@Repository :dao層
@Service:service層
@Controller:web層

3.依賴注入,給私有字段設置,也可以給setter方法設置

普通值:@Value("")
引用值:
    方式1:按照【類型】注入
        @Autowired
    方式2:按照【名稱】注入1
        @Autowired
        @Qualifier("名稱")
    方式3:按照【名稱】注入2
        @Resource("名稱")

4.生命週期

初始化:@PostConstruct
銷燬:@PreDestroy

5.作用域

@Scope("prototype") 多例

二.Resource註解(引用)

@Resource
    private Student student;
一定要啓動依賴注入的註解解析器 
   <context:annotation-config></context:annotation-config>

原理:

1.Spriing容器啓動的時候會創建在applicationContext.xml中的<bean>對象
2.Spring容器解析到context:annotation-config時,會在Spring管理的bean的範圍內查找這些類的屬性上是否有@Resource註解
3.Spring解析@Resource的name屬性,
    如果爲空,拿註解所在的屬性的名稱與Spring容器中的id去匹配,如果匹配成功則賦值,否則,按照類型去匹配,還沒有成功,就報錯。
    如果不爲空,則拿name的屬性值跟Spring容器中的id去匹配,不成功則報錯

三.掃描註解

@Component("student")
public class Student {
...
}

@Component("person")
public class Person {
    @Resource(name="student")
    private Student student;
    ...
}
配置文件中:
<context:component-scan base-package="com.spring.scan"></context:component-scan>

原理

1.啓動Spring容器,Spring容器解析配置文件
2.Spring解析到context:component-scan ,會在指定的base-package包及子包中掃描所有的類,看哪些類上有@Commonent註解
3.其實相當於將註解解析成<bean/>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章