SpringIoC基于注解的配置
- 前言
- 1.Spring配置檔案
- 2.IoC常用注解
- `@Component`
- `@Scope`
- `@Lazy`
- `@PostConstruct`、`@PreDestroy`
- `@Autowired`
- `@Qualifier`
- `@Resource`
- 總結
前言
在Spring容器中我們可以使用XML配置實作Bean的裝配,但是如果Bean過多,則會顯得XML檔案過于臃腫,為後續的工作造成了一定的困難,是以Spring提供了一種基于注解(Annotation)的裝配方式。
1.Spring配置檔案
因為Spring容器初始化時,隻會加載applicationContext.xml檔案,那麼我們在實體類中添加的注解就不會被Spring掃描,是以我們需要在applicationContext.xml聲明Spring的掃描範圍,以達到Spring初始化時掃描帶有注解的實體類并完成初始化工作
在配置applicationContext.xml想要使用context标簽聲明注解配置需要在原來配置的基礎上加context命名空間及相對應的限制。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--聲明使用注解配置,即開啟注解處理器-->
<context:annotation-config/>
<!--聲明Spring工廠注解的掃描範圍-->
<context:component-scan base-package="com.gyh.ioc.pojo"/>
</beans>
2.IoC常用注解
@Component
@Component
1.@Component:類注解,在實體類的位置加該注解,就表示将該實體類交給Spring容器管理,與bean作用相同。
2.@Component(value = “student”):value屬性用來指定目前bean的id,相當于bean的id,value也可以省略,這時候id的值預設為将類名的首字母小寫。(如:Student類首字母小寫為student)
3.與@Component功能相同的注解還有@Controller、@Service、@Repository
- @Controller注解 主要聲明将控制器類交給Spring容器管理(控制層)
- @Service注解 主要聲明将業務處理類交給Spring容器管理(Service層)
- @Repository注解 主要聲明持久化類交給Spring容器管理(DAO層)
- @Component 可以作用任何層次
@Scope
@Scope
1.@Scope:類注解,聲明目前類是單例模式還是原型模式,與bean标簽中的scope屬性作用相同。
2.@Scope(value = “prototype”)表示目前類是原型模式,不加value則預設為單例模式
@Lazy
@Lazy
1.@Lazy:類注解,用于聲明一個單例模式的bean屬于餓漢式還是懶漢式。
2.@Lazy(false):表示目前屬于bean是餓漢式,不添加值則預設為懶漢式。
@PostConstruct
、 @PreDestroy
@PostConstruct
@PreDestroy
1.@PostConstruct:方法注解,聲明一個方法為目前類的初始化方法,與bean标簽的init-method屬性作用相同,在構造方法執行後調用。
@PostConstruct
public void init(){
System.out.println("執行init方法!!!");
}
2.@PreDestroy:方法注解,聲明一個方法為目前類的銷毀方法,與bean标簽的destroy-method屬性作用相同,在Spring容器關閉時自動調用。
@PreDestroy
public void destroy(){
System.out.println("執行destroy方法!!!");
}
@Autowired
@Autowired
1.@Autowired:屬性注解、方法注解(setter方法),用于聲明目前屬性自動裝配,預設byType。
2.@Autowired(required = false):表示如果找不到與屬性類型相比對的類也不抛異常,而是給null。(預設為required = true 抛出異常)
@Qualifier
@Qualifier
1.@Qualifier:與@Autowired配合使用,會将預設的按Bean類型裝配改為按Bean的執行個體名稱裝配,Bean的執行個體名稱則由@Qualifier屬性指定,如下:
@Autowired(required = false)
public void setBook(@Qualifier("book1") Book book) {
this.book = book;
}
@Resource
@Resource
1.@Resource:屬性注解,用于聲明自動裝配,先按照byName查找,找不到之後按byType查找;如果都找不到或找到多個則抛出異常。