spring的純註解開發

2021-09-11 01:16:34 字數 2782 閱讀 5698

在config包下,建立乙個配置類springconfiguration,作用類似於bean.xml

spring中的新註解:

@configuration:(構造)//@configuration

@componentscan("com.itheima")

@import(jdbcconfig.class)

@propertysource("classpath:jdbcconfig.properties")

public class springconfiguration

@componentscans:可以配置多個@componentscan

@componentscan:(掃瞄元件)

作用:用於通過註解指定spring在建立容器時要掃瞄的包

屬性:value:它和basepackages的作用是一樣的,都是用於指定建立容器時要掃瞄的包。

我們使用此註解就等同於在xml中配置了:

@configuration

@componentscan("com.itheima")

@import(jdbcconfig.class)

@propertysource("classpath:jdbcconfig.properties")

public class springconfiguration

@bean:

作用:用於把當前方法的返回值作為bean物件存入spring的ioc容器中

屬性:name:用於指定bean的id。當不寫時,預設值是當前方法的名稱

細節:當我們使用註解配置方法時,如果方法有引數,spring框架會去容器中查詢有沒有可用的bean物件。

查詢的方式和autowired註解的作用是一樣的

@bean(name="ds1")

public datasource createdatasource1()catch (exception e)

}

@import (引入)

作用:,當子配置類不寫@configuration注釋時,import可以匯入其配置類

屬性:value:用於指定其他配置類的位元組碼。

當我們使用import的註解之後,有import註解的類就父配置類,而匯入的都是子配置類(更合理清晰)

@import(jdbcconfig.class)

或者也可以直接並列方式:

將資料庫的配置放到properties檔案中配置,再引用

jdbcconfig.properties

jdbc.driver=com.mysql.jdbc.driver

jdbc.url=jdbc:mysql://localhost:3306/eesy

jdbc.username=root

jdbc.password=1234

作用:用於指定properties檔案的位置

屬性:value:指定檔案的名稱和路徑。

關鍵字:classpath,表示類路徑下

//@configuration

@componentscan("com.itheima")

@import(jdbcconfig.class)

@propertysource("classpath:jdbcconfig.properties")

public class springconfiguration

和spring連線資料庫相關的配置類

*/public class jdbcconfig ")

private string driver;

@value("$")

private string url;

@value("$")

private string username;

@value("$")

private string password;

建立資料來源物件

* @return

*/@bean(name="ds2")

public datasource createdatasource()catch (exception e)

}

當有多個型別相同匹配的注入時**@qualifier:(取得資格的)**用在方法引數上,可以確定選用哪一條注入,此時可以單獨使用。

/**

* 用於建立乙個queryrunner物件

* @param datasource

* @return

*/@bean(name="runner")

@scope("prototype")

public queryrunner createqueryrunner(@qualifier("ds2") datasource datasource)

/** * 建立資料來源物件

* @return

*/@bean(name="ds2")

public datasource createdatasource()catch (exception e)

}@bean(name="ds1")

public datasource createdatasource1()catch (exception e)

}

Spring 純註解開發 001 基本註解學習

bean configuration conponentscans 配置類 configuration componentscans usedefaultfilters false public class myconfig bean name xiaoming public person pers...

Spring註解開發

spring註解開發 dao層用的註解 repository service層的註解 service controller表現層的註解 controller 以上的三個註解都是用 componment新增三個衍生的註解 屬性依賴注入 value的屬性注入 value wwtmy love 注入的是屬...

spring註解開發

第一步,設定xml約束檔案 第一步,設定xml約束檔案 xmlns xsi xmlns context xsi schemalocation spring beans.xsd spring context.xsd 第二步,定義bean 除了 component外,spring提供了3個功能基本和 c...