springIOC註解的使用
阿新 • • 發佈:2018-12-26
- 匯入context名稱控制元件約束
- 說明建立容器時要掃描的包
- 添加註解
- 使用
el
表示式,讀取properties
<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" >
<!--說明建立容器時掃描的包-->
<context:component-scan base-package="spring"></context:component-scan>
<!--指定properties檔案位置-->
<context:property-placeholder location="spring-properties.properties" />
</beans>
在需要new的對像的類上添加註解,將物件放入spring容器中
@Component(value = "accountService")
public class AccountServiecImp implements IAccountService {
}
讀取的方式仍然相同
public class Client {
public static void main(String[] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-bean.xml");
IAccountService accountService = ac.getBean ("accountService",IAccountService.class);
System.out.println(accountService);
}
}
註解分類
用於建立物件
@Component
:相當於spring的xml檔案當中寫bean標籤;它的value屬性指定bean的id;不寫時物件名稱預設為類名首字母小寫。
由它衍射的還有Controller
(表現層)、Service
(業務層)、Repsitory
(持久層);它們繼承Component使用相同的方法;區別在於提供更明確的語義化來指定不同層的物件。
若屬性只是用value,則可省略只寫名稱
用於注入資料
注入資料的作用就是為物件的屬性賦值;不然屬性只是聲明瞭變數/物件型別沒有具體值。
@Autowired
:自動按照型別注入,只要bean容器中有唯一型別匹配(bean物件的型別和宣告的物件型別匹配),則直接注入成功;若有多種物件型別匹配(實現相同介面),則按照變數名稱和bean中物件id匹配;該註解可以省略set方法
其屬性require="true/false"
標識是否必須注入成功,報錯內容不同而已;寫不寫沒啥大影響,預設有該屬性並且為true。@Qualifier(value = "beanId")
在Autowired
下使用,指定bean物件id;不能單獨使用@Resource(name = "beanId")
以上三種只能用來注入bean物件型別,不能注入基礎資料型別或集合。@Value
:用於注入基本型別和String型別;其屬性為value指定要注入的資料,並支援spring的el表示式:${表示式}
用於改變作用範圍
@Scope
:值:預設singleton
,prototype
和xml檔案中的該屬性相同
和生命週期相關
@PostContruct
:用於指定初始化方法,和配置檔案中的init-method屬性是一樣的@PreDestroy
:用於指定銷燬方法,和配置檔案中的destroy-method屬性一樣
配置類,代替XML
直接讀取配置註解類
ApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfiguration.class);
Configuration
:表明當前類是spring的配置類;如果只是寫到AnnotationConfigApplicationContext建構函式中的位元組碼,則可以省略;如果沒有寫到建構函式中,但是在載入要掃描的包時,需要讀到此配置,則必須寫。Bean(name="objectName")
:把當前方法的返回值存入spring的容器中;屬性name用於指定bean的id,預設為當前方法名稱。Qualifier
:Spring框架給帶有bean註解的方法建立建立物件時,如果方法有引數,會用方法引數的資料型別前往容器中查詢;如果有唯一的一個型別匹配,則直接給方法的引數注入。如果找到多個,則使用該註解,該註解也可以獨立使用。ComponentScan(name="backageName")
:用於指定spring要掃描的包。Import(value="Class<?>[]")
:用於匯入其他的配置類PropertySource("xxx.properties")
:讀取properties配置檔案,結合el表示式使用