日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring IOC基本配置(xml配置和注解配置)

發(fā)布時間:2025/3/11 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring IOC基本配置(xml配置和注解配置) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

目錄

  • Spring IOC
    • IOC是什么
    • IOC可以做什么
    • 依賴注入
    • IOC和DI
    • IOC容器
    • Bean
  • 配置IOC容器
    • spring ioc 依賴
    • XML配置
    • 實例化容器
    • 使用容器
    • xml配置詳解
      • spring對bean的管理
        • 1、創(chuàng)建bean的三種方式
        • 2、bean對象的作用范圍
        • 3、bean對象的生命周期
      • 構(gòu)造函數(shù)依賴注入
      • Setter方法依賴注入
    • 注解配置
      • 使用xml和注解配置
        • xml配置
        • @Component、@Controller、@Service、@Repository
        • 用于注入數(shù)據(jù)的注解
          • @Autowired
          • @Qualifier
          • @Resource
          • 關(guān)于@Autowired、@Qualifier、@Resource
          • @Value
        • 用于指定作用范圍的注解 @Scope
        • 與生命周期相關(guān)的注解 @PreDestroy、@PostConstruct
      • 使用注解配置
        • 使用@Configuration
        • @ComponentScan
        • @Bean
        • @Import
        • @PropertySource
    • 注解配置案例
        • Maven 依賴
        • domain
        • 配置類
          • 主配置類
          • 子配置類
        • jdbc.properties
        • 持久層
          • IAccountDao
          • IAccountDaoimpl
        • 業(yè)務(wù)層
          • IAccountService
          • IAccountServiceimpl
        • 測試類

Spring IOC

IOC是什么

IOC是 Inversion of Control 的縮寫,即控制反轉(zhuǎn)。

  • 上層模塊不應(yīng)該依賴于下層模塊,它們共同依賴于一個抽象
  • 抽象不能依賴于具體實現(xiàn),具體實現(xiàn)依賴于抽象

IoC 不是什么技術(shù),而是一種設(shè)計思想。在 Java 開發(fā)中,IoC 意味著將你設(shè)計好的對象交給容器控制,而不是傳統(tǒng)的在你的對象內(nèi)部直接控制。如何理解 Ioc 呢?理解 Ioc 的關(guān)鍵是要明確“誰控制誰,控制什么,為何是反轉(zhuǎn)(有反轉(zhuǎn)就應(yīng)該有正轉(zhuǎn)了),哪些方面反轉(zhuǎn)了”,那我們來深入分析一下:
誰控制誰,控制什么:傳統(tǒng) JavaSE 程序設(shè)計,我們直接在對象內(nèi)部通過 new 進行創(chuàng)建對象,是程序主動去創(chuàng)建依賴對象;而 IoC 是有專門一個容器來創(chuàng)建這些對象,即由 IoC 容器來控制對象的創(chuàng)建;誰控制誰?當(dāng)然是 IoC 容器控制了對象;控制什么?那就是主要控制了外部資源獲取(不只是對象包括比如文件等)。
為何是反轉(zhuǎn),哪些方面反轉(zhuǎn)了:有反轉(zhuǎn)就有正轉(zhuǎn),傳統(tǒng)應(yīng)用程序是由我們自己在對象中主動控制去直接獲取依賴對象,也就是正轉(zhuǎn);而反轉(zhuǎn)則是由容器來幫忙創(chuàng)建及注入依賴對象;為何是反轉(zhuǎn)?因為由容器幫我們查找及注入依賴對象,對象只是被動的接受依賴對象,所以是反轉(zhuǎn);哪些方面反轉(zhuǎn)了?依賴對象的獲取被反轉(zhuǎn)了。
----轉(zhuǎn)載自github的一篇博客。

未使用IOC容器前

使用IOC容器后

IOC可以做什么

IoC 不是一種技術(shù),只是一種思想,一個重要的面向?qū)ο缶幊痰姆▌t,它能指導(dǎo)我們?nèi)绾卧O(shè)計出松耦合、更優(yōu)良的程序。傳統(tǒng)應(yīng)用程序都是由我們在類內(nèi)部主動創(chuàng)建依賴對象,從而導(dǎo)致類與類之間高耦合,難于測試;有了 IoC 容器后,把創(chuàng)建和查找依賴對象的控制權(quán)交給了容器,由容器進行注入組合對象,所以對象與對象之間是松散耦合,這樣也方便測試,利于功能復(fù)用,更重要的是使得程序的整個體系結(jié)構(gòu)變得非常靈活。
其實 IoC 對編程帶來的最大改變不是從代碼上,而是從思想上,發(fā)生了“主從換位”的變化。應(yīng)用程序原本是老大,要獲取什么資源都是主動出擊,但是在 IoC/DI 思想中,應(yīng)用程序就變成被動的了,被動的等待 IoC 容器來創(chuàng)建并注入它所需要的資源了。
IoC 很好的體現(xiàn)了面向?qū)ο笤O(shè)計法則之一—— 好萊塢法則:“別找我們,我們找你”;即由 IoC 容器幫對象找相應(yīng)的依賴對象并注入,而不是由對象主動去找。
----轉(zhuǎn)載自github的一篇博客。

依賴注入

DI,是 Dependency Injection 的縮寫,即依賴注入。
依賴注入是 IoC 的最常見形式。
容器全權(quán)負責(zé)的組件的裝配,它會把符合依賴關(guān)系的對象通過 JavaBean 屬性或者構(gòu)造函數(shù)傳遞給需要的對象。

DI 是組件之間依賴關(guān)系由容器在運行期決定,形象的說,即由容器動態(tài)的將某個依賴關(guān)系注入到組件之中。依賴注入的目的并非為軟件系統(tǒng)帶來更多功能,而是為了提升組件重用的頻率,并為系統(tǒng)搭建一個靈活、可擴展的平臺。通過依賴注入機制,我們只需要通過簡單的配置,而無需任何代碼就可指定目標(biāo)需要的資源,完成自身的業(yè)務(wù)邏輯,而不需要關(guān)心具體的資源來自何處,由誰實現(xiàn)。

理解 DI 的關(guān)鍵是:“誰依賴誰,為什么需要依賴,誰注入誰,注入了什么”,那我們來深入分析一下:
誰依賴于誰:當(dāng)然是應(yīng)用程序依賴于 IoC 容器;
為什么需要依賴:應(yīng)用程序需要 IoC 容器來提供對象需要的外部資源;
誰注入誰:很明顯是 IoC 容器注入應(yīng)用程序某個對象,應(yīng)用程序依賴的對象;
注入了什么:就是注入某個對象所需要的外部資源(包括對象、資源、常量數(shù)據(jù))。

IOC和DI

其實它們是同一個概念的不同角度描述,由于控制反轉(zhuǎn)概念比較含糊(可能只是理解為容器控制對象這一個層面,很難讓人想到誰來維護對象關(guān)系),所以 2004 年大師級人物 Martin Fowler 又給出了一個新的名字:“依賴注入”,相對 IoC 而言,“依賴注入”明確描述了“被注入對象依賴 IoC 容器配置依賴對象”。

IOC容器

其實它們是同一個概念的不同角度描述,由于控制反轉(zhuǎn)概念比較含糊(可能只是理解為容器控制對象這一個層面,很難讓人想到誰來維護對象關(guān)系),所以 2004 年大師級人物 Martin Fowler 又給出了一個新的名字:“依賴注入”,相對 IoC 而言,“依賴注入”明確描述了“被注入對象依賴 IoC 容器配置依賴對象”。

Bean

JavaBean 是一種 JAVA 語言寫成的可重用組件。為寫成 JavaBean,類必須是具體的和公共的,并且具有無參數(shù)的構(gòu)造器。JavaBean 對外部通過提供 getter / setter 方法來訪問其成員。

由 IoC 容器管理的那些組成你應(yīng)用程序的對象我們就叫它 Bean。Bean 就是由 Spring 容器初始化、裝配及管理的對象,除此之外,bean 就與應(yīng)用程序中的其他對象沒有什么區(qū)別了。那 IoC 怎樣確定如何實例化 Bean、管理 Bean 之間的依賴關(guān)系以及管理 Bean 呢?這就需要配置元數(shù)據(jù),在 Spring 中由 BeanDefinition 代表,后邊會詳細介紹,配置元數(shù)據(jù)指定如何實例化 Bean、如何組裝 Bean 等。

配置IOC容器

IoC 容器的配置有三種方式:

  • 基于 xml 配置
  • 基于注解配置
  • 基于 Java 配置

spring ioc 依賴

首先我們先導(dǎo)入maven的spring ioc依賴

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.0.RELEASE</version></dependency> </dependencies>

XML配置

首先創(chuàng)建一個spring ioc 的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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <bean id="UserService" class="com.service.Impl.IUserServiceimpl"> </bean><import resource="bean2.xml" /> </beans>

標(biāo)簽說明:

  • <beans> 是 Spring 配置文件的根節(jié)點。
  • <bean>用來定義一個 JavaBean。id 屬性是它的標(biāo)識,在文件中必須唯一;class 屬性是它關(guān)聯(lián)的類。
  • <import /> 用來導(dǎo)入其他配置文件的 Bean 定義。這是為了加載多個配置文件。

實例化容器

核心容器的兩個接口

  • ApplicationContext: 單例對象適用
    它在構(gòu)建核心容器時,創(chuàng)建對象采取的策略是采用立即加載的方式。也就是說,只要一讀取完配置文件馬上就創(chuàng)建配置文件中配置的對象
  • BeanFactory: 多例對象適用
    它在構(gòu)建核心容器時,創(chuàng)建對象采取的策略是采用延時加載的方式。也就是說,只有通過id獲取對象時,才真正的創(chuàng)建對象

實例化容器的過程: 定位資源(XML 配置文件) 讀取配置信息(Resource) 轉(zhuǎn)化為 Spring 可識別的數(shù)據(jù)形式(BeanDefinition)。

ApplicationContext context =new ClassPathXmlApplicationContext(new String[] {"bean1.xml", "bean2.xml"});

組合 xml 配置文件 配置的 Bean 功能各不相同,都放在一個 xml 文件中,不便管理。 Java 設(shè)計模式講究職責(zé)單一原則。配置其實也是如此,功能不同的 JavaBean 應(yīng)該被組織在不同的 xml 文件中。然后使用 import 標(biāo)簽把它們統(tǒng)一導(dǎo)入。

ApplicationContext是一個接口 有常用的三個實現(xiàn)類

  • 1、ClassPathXmlApplicationContext
    • 它可以加載類路徑下的配置文件,要求配置文件必須要在類路徑下。
    • ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"bean1.xml", "bean2.xml"});
  • 2、FileSystemXmlApplicationContext
    • 它可以加載磁盤任意路徑下的配置文件(前提是必須有訪問權(quán)限)
  • 3、AnnotationConfigApplicationContext
    • 它用于讀取注解創(chuàng)建容器的。
    • new AnnotationConfigApplicationContext(Class<?> ... config);
    • ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);

使用容器

使用容器的方式就是通過getBean獲取 IoC 容器中的 JavaBean。
第一種 getBean(String id)
第二種 getBean(String id, Class<?> object)

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");IUserService iUserService1 = (IUserServiceimpl) applicationContext.getBean("IUserService");IUserService iUserService2 = applicationContext.getBean("IUserService", IUserService.class);

xml配置詳解

spring對bean的管理

1、創(chuàng)建bean的三種方式

  • 使用默認構(gòu)造函數(shù)(無參)創(chuàng)建對象

    • 在使用spring配置文件中使用bean標(biāo)簽時,配以id和class屬性之后并且沒有其他屬性和標(biāo)簽時,采用的就是默認構(gòu)造函數(shù)創(chuàng)建bean對象,此時如果類中沒有默認構(gòu)造函數(shù),則對象無法創(chuàng)建。
  • 使用普通工廠中的方法創(chuàng)建對象(使用某個類中的方法創(chuàng)建對象,并存入spring容器)

    • id為需要創(chuàng)建的對象的id(需要為目標(biāo)對象配bean),factory-bean屬性為工廠類的id(先給工廠類配bean),factory-method屬性為工廠類創(chuàng)建目標(biāo)對象的方法(該方法不能為static)
  • 使用普通工廠中的靜態(tài)(static)方法創(chuàng)建對象(使用某個類中的靜態(tài)(static)方法創(chuàng)建對象,并存入spring容器)

    • class屬性為工廠的全限定類名,這也代表著bean創(chuàng)建的id對應(yīng)的是工廠類, 但是設(shè)置factory-method屬性為工廠類創(chuàng)建目標(biāo)對象的靜態(tài)(static)方法,這樣就會默認調(diào)用該方法,返回的就是目標(biāo)對象。

使用默認構(gòu)造函數(shù)(無參)創(chuàng)建對象

<bean id="UserService" class="com.service.Impl.IUserServiceimpl"> </bean>

使用普通工廠中的方法創(chuàng)建對象

<bean id="instanceFactory" class="com.factory.InstanceFactory"></bean><bean id="IUserService" factory-bean="instanceFactory" factory-method="getIUserSevice" ></bean>

使用普通工廠中的靜態(tài)(static)方法創(chuàng)建對象

<bean id="IUserService" class="com.factory.staticFactory" factory-method="getIUserSevice"></bean>

2、bean對象的作用范圍

默認情況下 bean對象只創(chuàng)建一次————————單例對象。我們可以通過bean標(biāo)簽的scope屬性設(shè)置bean對象的作用范圍。
scope屬性:

  • 作用:用于指定bean的作用范圍
  • 取值:
    • singleton:單例的(默認值)
    • prototype:多例的
    • request:作用于web應(yīng)用的請求范圍
    • session:作用于web應(yīng)用的會話范圍
    • global-session:作用于集群環(huán)境的會話范圍(全局會話范圍)。當(dāng)不是集群環(huán)境時,與session等同

3、bean對象的生命周期

1、單例對象:

  • 出生:當(dāng)容器創(chuàng)建時對象出生
  • 活著:只要容器沒有銷毀,對象一直活著
  • 死亡:當(dāng)容器銷毀,對象跟著死亡
  • 總結(jié):單例對象的生命周期與容器相同

2、多例對象:

  • 出生:當(dāng)我們使用對象時spring框架為我們創(chuàng)建
  • 活著:對象只要在使用過程中就一直活著
  • 死亡:當(dāng)對象長時間未使用且沒有其他對象引用時,java垃圾回收機制會自動回收對象

我們可以借助bean標(biāo)簽的init-method屬性調(diào)用初始化方法和destroy-method調(diào)用銷毀方法

//init 和 destroy 是類IUserServiceimpl 定義的方法 <bean id="IUserService" class="com.service.Impl.IUserServiceimpl" scope="singleton" init-method="init" destroy-method="destroy"></bean>

構(gòu)造函數(shù)依賴注入

  • 使用的標(biāo)簽:<constructor-arg></constructor-arg>
  • 標(biāo)簽出現(xiàn)的位置:bean標(biāo)簽內(nèi)部
  • 標(biāo)簽的屬性:
    • name:用于指定給構(gòu)造函數(shù)中指定名稱的參數(shù)賦值
    • index:用于指定需要注入的數(shù)據(jù)給構(gòu)造函數(shù)中指定索引位置的參數(shù)賦值
    • type:用于指定需要注入的數(shù)據(jù)類型,該數(shù)據(jù)類型也是構(gòu)造函數(shù)中某個或者某些參數(shù)的類型
    • value:用于指定基本類型和String類型的數(shù)據(jù)
    • ref:用于指定其他bean類型數(shù)據(jù)。它指的就是在Spring的ioc核心容器中出現(xiàn)過的bean對象
<bean id="IUserService" class="com.service.Impl.IUserServiceimpl" ><constructor-arg name="name" value="xiuyuandashen"></constructor-arg><constructor-arg name="age" value="18"></constructor-arg><constructor-arg name="birthday" ref="birthday"></constructor-arg> </bean> <bean id="birthday" class="java.util.Date"></bean>

對應(yīng)的構(gòu)造函數(shù)

public IUserServiceimpl(String name, Date birthday, Integer age) {this.name = name;this.birthday = birthday;this.age = age;}

Setter方法依賴注入

首先該對象得Setter方法

  • 使用的標(biāo)簽:property
  • 標(biāo)簽出現(xiàn)的位置:bean標(biāo)簽內(nèi)部
  • 標(biāo)簽的屬性:
    • name:用于指定給set方法名稱
    • value:用于指定基本類型和String類型的數(shù)據(jù)
    • ref:用于指定其他bean類型數(shù)據(jù)。它指的就是在Spring的ioc核心容器中出現(xiàn)過的bean對象

復(fù)雜類型的注入或者集合結(jié)構(gòu)類型的注入

  • 使用的標(biāo)簽:property
  • 標(biāo)簽出現(xiàn)的位置:bean標(biāo)簽內(nèi)部
  • 用于給list結(jié)構(gòu)集合注入的標(biāo)簽:
    • <array> <list> <set>
    • 注意,結(jié)構(gòu)相同標(biāo)簽可以互換
  • 用于給map結(jié)構(gòu)集合注入的標(biāo)簽
    • <map> <props>
    • 注意,結(jié)構(gòu)相同標(biāo)簽可以互換
<bean id="fuzajiegou" class="com.domain.fuzajiegou"><property name="myArr"><array><value>hello</value><value>world</value><value>java</value><value>javaScript</value></array></property><property name="myList"><list><value>list——a</value><value>list——b</value><value>list——c</value><value>list——e</value><value>list——f</value></list></property><property name="mySet"><set><value>set——a</value><value>set——b</value><value>set——c</value><value>set——e</value><value>set——f</value></set></property><property name="myMap"><map><entry key="map1" value="1"></entry><entry key="map2" value="2"></entry><entry key="map3" value="3"></entry><entry key="map4"><value>4</value></entry></map></property><property name="myPro"><props><prop key="Properties1">1</prop><prop key="Properties2">2</prop><prop key="Properties3">3</prop><prop key="Properties4">4</prop></props></property></bean>

對應(yīng)的bean類

public class fuzajiegou {private String[] myArr;private List myList;private Set mySet;private Properties myPro;private Map<String,String> myMap;public void setMyArr(String[] myArr) {this.myArr = myArr;}public void setMyList(List myList) {this.myList = myList;}public void setMySet(Set mySet) {this.mySet = mySet;}public void setMyPro(Properties myPro) {this.myPro = myPro;}public void setMyMap(Map<String, String> myMap) {this.myMap = myMap;} } public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");final fuzajiegou fuzajiegou = applicationContext.getBean("fuzajiegou", fuzajiegou.class);System.out.println(fuzajiegou);}

注解配置

使用xml和注解配置

xml配置

Spring 默認是不啟用注解的。如果想使用注解,需要先在 xml 中啟動注解。 啟動方式:在 xml 中加入一個標(biāo)簽,很簡單吧。

<?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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com"/></beans>

標(biāo)簽說明:

  • <context:component-scan base-package="com"/> 標(biāo)簽
    • 屬性base-package 表示掃描的位置

@Component、@Controller、@Service、@Repository

@Component 注解

  • 作用:用于將當(dāng)前類對象存入spring容器
  • 屬性:
    • value:用于指定<bean>的id。當(dāng)我們不寫時默認為當(dāng)前類名,且首字母小寫

@Controller、@Service、@Repository 注解

  • 以上這三種的作用和屬性與@Component一樣,用這三種注解使三層結(jié)構(gòu)對象更清晰。
  • @Controller 表示表現(xiàn)層
  • @Service 表示業(yè)務(wù)層
  • @Repository 表示持久層

用于注入數(shù)據(jù)的注解

他們的作用就和xml配置文件中的bean標(biāo)簽中寫一個<property></property>標(biāo)簽的作用是一樣的

@Autowired

@Autowired

  • 作用:自動按照類型注入。只需要容器中有唯一的一個bean對象類型和要注入的變量匹配,就可以注入成功。 如果ioc容器中沒有任何bean的類型與要注入的變量類型匹配,則報錯。
  • 細節(jié):
    • 如果ioc容器中有多個類型匹配時:先按照變量類型找出所有,然后將變量名稱作為id進行查找對應(yīng)的對象/值。
@Qualifier
  • 作用:在按照類型注入的基礎(chǔ)(@Autowired)上再按照名稱注入。
  • 細節(jié):
    • 它在給類成員注入時不能單獨使用。
    • 但是在給方法參數(shù)注入時可以單獨使用。
  • 屬性:
    • value:用于指定注入bean的id。
@Resource
  • 作用:直接按照bean的id注入。它可以單獨使用。
  • 屬性:
    • name:用于指定bean的id
關(guān)于@Autowired、@Qualifier、@Resource

以上三種注解(@Autowired、@Qualifier、@Resource)都只能注入其他bean類型的數(shù)據(jù),而基本類型和String類型無法使用上述三種注解實現(xiàn)

@Value
  • 作用:用于注入基本類型和String類型的數(shù)據(jù)
  • 屬性:
    • value:用于指定數(shù)據(jù)的值。它可以使用spring中的el表達式(spEL)。spEl的寫法:${表達式}

用于指定作用范圍的注解 @Scope

他們的作用就和bean標(biāo)簽中使用scope屬性實現(xiàn)的功能一致。
@Scope

  • 作用:用于指定bean的作用范圍
  • 屬性:
    • value:指定范圍的取值。常用取值:singleton(單例),prototype(多例)…

與生命周期相關(guān)的注解 @PreDestroy、@PostConstruct

他們的作用就和bean標(biāo)簽中使用scope屬性實現(xiàn)的功能一致。
@PreDestroy

  • 作用:用于指定銷毀方法
    @PostConstruct
  • 作用:用于指定初始化方法

使用注解配置

首先使用注解配置需要解決xml配置文件中注解對<context:component-scan base-package="com"/>的依賴
我們可以使用@ComponentScan注解來代替<context:component-scan base-package="com"/>

使用@Configuration

@Configuration

  • 作用:指定當(dāng)前類是一個配置類
  • 細節(jié):當(dāng)該配置類作為AnnotationConfigApplicationContext對象創(chuàng)建的參數(shù)時,該注解可以不寫。

@ComponentScan

@ComponentScan

  • 作用:用于通過注解指定spring在創(chuàng)建容器時要掃描的包
  • 屬性:
    • basePackages:它和value的作用是一致的,都是用于指定創(chuàng)建容器時需要掃描的包,我們使用此注解就等同于在xml配置了:<context:component-scan base-package=""/>.
    • value:與basePackages一樣
    • 以上兩個屬性的值都是一個String[]數(shù)組。數(shù)組的每個值表示要掃描的包名。
  • 細節(jié):
    • 被掃描的包中的類需要被掃描到的話需要加上 @Configuration 注解。

@Bean

  • 作用:用于將當(dāng)前方法的返回值作為bean對象存入spring的IOC容器中。
  • 屬性:
    • name:用于指定bean的id。當(dāng)不寫name時,默認值為當(dāng)前方法的名稱。
  • 細節(jié):
    • 當(dāng)我們使用注解配置方法時,如果方法有參數(shù),spring框架會去容器中查找有沒有可用的bean對象。 查找的方式和 @Autowired注解的作用是一致的。使用@Bean注解默認是單例的,需要加個@Scope("prototype")指明為多例對象

@Import

  • 作用:用于導(dǎo)入其他的配置類。
  • 屬性:
    • Class []value:該數(shù)組的值就是需要引入的其他配置類的字節(jié)碼文件。
  • 細節(jié):
  • 當(dāng)類被其他類用@Import 注解引入時,該類就不需要用 @Configuration來指明是配置類.相當(dāng)于,使用@Import的配置類為父配置類,引入的類就是子配置類.在使用AnnotationConfigApplicationContext對象創(chuàng)建IOC容器時只需要引入父配置類即可。

@PropertySource

  • 作用:用于指定Properties文件的位置
  • 屬性:
    • String []value:指定文件的路徑和名稱。關(guān)鍵詞:classpath 表示類路徑下。例如 @PropertySource("classpath:jdbc.properties")

注解配置案例

這是一個單表CRUD的案例。
項目結(jié)構(gòu)

Maven 依賴

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.14</version></dependency><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.6</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version><scope>test</scope></dependency></dependencies>

domain

package com.domain;public class Account {private Integer id;private String name;private double money;public Account() {}public Account(String name, double money) {this.name = name;this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getMoney() {return money;}public void setMoney(double money) {this.money = money;} }

配置類

主配置類
package com.config;import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.*;import javax.sql.DataSource; @Configuration @ComponentScan(basePackages = {"com.Dao","com.service"}) @Import({jdbcConfig.class}) @PropertySource({"classpath:jdbc.properties"}) public class SpringConfiguration {}
子配置類
package com.config;import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Scope;import javax.sql.DataSource;public class jdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.jdbcUrl}")private String jdbcUrl;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;/*** dbUtils* @param dataSource* @return*/@Bean(name = "runner")@Scope("prototype")public QueryRunner createQueryRunner(DataSource dataSource) {return new QueryRunner(dataSource);}/*** 配置數(shù)據(jù)源* @return*/@Bean(name = "dataSource")public DataSource createDataSource() {try {ComboPooledDataSource ds = new ComboPooledDataSource();ds.setDriverClass(driver);ds.setJdbcUrl(jdbcUrl);ds.setUser(username);ds.setPassword(password);return ds;} catch (Exception e) {throw new RuntimeException(e);}}}

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql://localhost:3306/zlf?serverTimezone=UTC jdbc.username=root jdbc.password=feng10.10

持久層

IAccountDao
package com.Dao;import com.domain.Account;import java.util.List;/***賬戶的持久層接口**/ public interface IAccountDao {/*** 查詢所有* @return*/List<Account> selAll();/*** 查詢一個* @param id* @return*/Account findAccountbyid(int id);/*** 保存* @param account*/void saveAccount(Account account);/***更新* @param account*/void updateAccount(Account account);/*** 刪除* @param id*/void deleteAccount(int id) throws Exception; }
IAccountDaoimpl
package com.Dao.Impl;import com.Dao.IAccountDao; import com.domain.Account; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;import java.util.List;/*** 賬戶的持久層實現(xiàn)類*/ @Repository("IAccountDao") public class IAccountDaoimpl implements IAccountDao {@Autowiredprivate QueryRunner runner;public void setRunner(QueryRunner runner) {this.runner = runner;}public List<Account> selAll() {try{return runner.query("select *from account",new BeanListHandler<Account>(Account.class));}catch (Exception e){throw new RuntimeException(e);}}public Account findAccountbyid(int id) {try{return runner.query("select *from account where id=?",new BeanHandler<Account>(Account.class),id);}catch (Exception e){throw new RuntimeException(e);}}public void saveAccount(Account account) {try{runner.update("insert into account(name,money) values(?,?)" ,account.getName(),account.getMoney());}catch (Exception e){throw new RuntimeException(e);}}public void updateAccount(Account account) {try{runner.update("update account set name=? ,money=? where id=?" ,account.getName(),account.getMoney(),account.getId());}catch (Exception e){throw new RuntimeException(e);}}public void deleteAccount(int id) {try {runner.update("delete from account where id=?",id);}catch (Exception e){throw new RuntimeException(e);}} }

業(yè)務(wù)層

IAccountService
package com.service;import com.domain.Account;import java.util.List;/*** 賬戶的業(yè)務(wù)層接口*/ public interface IAccountService {/*** 查詢所有* @return*/List<Account> selAll();/*** 查詢一個* @param id* @return*/Account findAccountbyid(int id);/*** 保存* @param account*/void saveAccount(Account account);/***更新* @param account*/void updateAccount(Account account);/*** 刪除* @param id*/void deleteAccount(int id) throws Exception;}
IAccountServiceimpl
package com.service.Impl;import com.Dao.IAccountDao; import com.Dao.Impl.IAccountDaoimpl; import com.domain.Account; import com.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import java.util.List; @Service("IAccountService") public class IAccountServiceimpl implements IAccountService {@Autowiredprivate IAccountDao iAccountDao;public List<Account> selAll() {return iAccountDao.selAll();}public Account findAccountbyid(int id) {return iAccountDao.findAccountbyid(id);}public void saveAccount(Account account) {iAccountDao.saveAccount(account);}public void updateAccount(Account account) {iAccountDao.updateAccount(account);}public void deleteAccount(int id) throws Exception {iAccountDao.deleteAccount(id);}public void setiAccountDao(IAccountDaoimpl iAccountDao) {this.iAccountDao=iAccountDao;} }

測試類

package com.test;import com.config.SpringConfiguration; import com.domain.Account; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.service.IAccountService; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.sql.DataSource; import java.util.List;public class accountServiceTest {IAccountService iAccountService = null;@Beforepublic void init() throws Exception {final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);iAccountService = applicationContext.getBean("IAccountService", IAccountService.class);}/*** 查詢所有*/@Testpublic void findAll() {System.out.println(iAccountService.selAll());}/*** 查詢一位*/@Testpublic void findOne() {System.out.println(iAccountService.findAccountbyid(2));}/*** 保存*/@Testpublic void TestSave() {iAccountService.saveAccount(new Account("小明", 1002.5));}/*** 更新*/@Testpublic void TestUpadata() {final Account account = iAccountService.findAccountbyid(4);account.setMoney(100002.5);iAccountService.updateAccount(account);}/*** 刪除** @throws Exception*/@Testpublic void Testdalete() throws Exception {iAccountService.deleteAccount(4);}}

總結(jié)

以上是生活随笔為你收集整理的spring IOC基本配置(xml配置和注解配置)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。