[Spring]spring的工作原理以及注入方式簡介

Spring 工作原理

         spring是一個用於web服務的框架,可以用於將struts2和hibernate進行整合,並且可以配置各種bean,和維護beanbean之間的關係主要採用面向切面(AOP)和控制反轉(IOC)的方法,也就是反射,降低了項目的耦合度。

Spring 注入方式

     這裏主要介紹三種,分別爲

  1. set方式
  2. constructor方式
  3. autowired方式

     1.set方式

       也就是通過set方法將屬性注入,如下圖所示

                                  

 2.constructor方式

  

 

3.註解模式

           這個註解最開始一直都不生效,就是缺少了關鍵性的這一個<context:annotation-config/>。其實註解並沒有啥實質性的操作,主要是靠這個配置來作爲工具去表明需要怎樣掃描注入。主要的作用就是激活在spring中註冊過的bean.

         與這個註解很相像的另一個註解<context:component-scan>除了具有<context:annotation-config />的功能之外,還具有自動將帶有@component,@service,@Repository等註解的對象註冊到spring容器中的功能,也就是說我們配置好要掃描的包之後,可以不寫任何的bean

<context:component-scan base-package="com.xxx"/>

如果兩者都進行配置的話,則<context:annotation-config />會被忽略,並不會出現重複注入的問題。

具體配置內容如下圖所示

   

<?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.xsd

  http://www.springframework.org/schema/context

                        http://www.springframework.org/schema/context/spring-context.xsd

">
    <!--
每個配置文件必須的部分,也就是spring的根本。-->
    <!--  聲明xml文件默認的命名空間,表示未使用其他命名空間的所有標籤的默認命名空間。-->
    <!--  聲明XML Schema 實例,聲明後就可以使用 schemaLocation 屬性了。-->
    <!-- xsi:schemaLaction部分: 是爲上面配置的命名空間指定xsd規範文件,這樣你在進行下面具體配置的時候就會根據這些xsd規範文件給出相應的提示,-->
    <!--比如說每個標籤是怎麼寫的,都有些什麼屬性是都可以智能提示的,-->
    <!--以防配置中出錯而不太容易排查,在啓動服務的時候也會根據xsd規範對配置進行校驗。-->
    <!--但是這裏需要爲你上面xmlns裏面配置的mvc、aop、tx等都配置上xsd規範文件。-->
 
  <context:annotation-config/>
    <bean id="student" class="bean.Student" autowire="byType">
        <property name="name" value="Hello World!"></property></bean>
    <bean id="helloWorld" class="bean.HelloWorld"></bean>
</beans>

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章