Spring之Bean的管理方式(Content,Beans)

Spring的bean管理(註釋)

註解

  1. 代碼裏特殊的標記,使用註解也可以直接完成相關功能

  2. 註解寫法:@註解名稱(屬性名=屬性值)

  3. 使用在類,方法,屬性上面

Spring註解開發準備

  1. 導入jar包

    (1)導入基本的jar包

    (2)導入aop的jar包

  2. 創建類(bean)

  3. 創建Spring的配置文件

    (1)beans約束

    (2)新約束,docs->html->schema: context 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 https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
  4. 配置文件中

 <!--    開啓註解掃描-->
       <context:component-scan base-package="service"/>
<!--只掃描屬性上的註釋-->
       <context:annotation-config></context:annotation-config> 
   

註解創建對象

@Component組件(作用在類上)

Spring中提供**@Component**的三個衍生註解:(功能目前來看是一致的)

註解名 作用範圍
@Controller WEB層
@Service 業務層
@Repository 持久層

使用方法:在類上加對象

@Component(value = "bean")//value中爲bean的id

創建對象單實例還是多實例:@Scope

默認是singleton

@Scope(value=“prototype”)

自動裝配註解

@Autowired

標註在屬性之上,自動根據類名稱尋找對象並注入

@Resource

@Resource有兩種

標註在屬性之上,指定對象注入

種類 區別
@Resource(name=“注入對象的id”) 根據對象的名字(id)注入
@Resource(type=“注入對象的id”) 根據對象的類型注入
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章