Spring(8) 使用註解開發
阿新 • • 發佈:2022-05-11
8.使用註解開發
8.1使用註解定義 Bean
Spring 提供了以下多個註解,這些註解可以直接標註在 Java 類上,將它們定義成 Spring Bean。
註解 | 說明 |
---|---|
@Component | 該註解用於描述 Spring 中的 Bean,它是一個泛化的概念,僅僅表示容器中的一個元件(Bean),並且可以作用在應用的任何層次,例如 Service 層、Dao 層等。 使用時只需將該註解標註在相應類上即可。 |
@Repository | 該註解用於將資料訪問層(Dao 層)的類標識為 Spring 中的 Bean,其功能與 @Component 相同。 |
@Service | 該註解通常作用在業務層(Service 層),用於將業務層的類標識為 Spring 中的 Bean,其功能與 @Component 相同。 |
@Controller | 該註解通常作用在控制層(如 Struts2 的 Action、SpringMVC 的 Controller),用於將控制層的類標識為 Spring 中的 Bean,其功能與 @Component 相同。 |
在Spring4之後,要使用註解開發,必須要保證aop的包匯入,由於我是基於Maven實現
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.14</version> </dependency>
使用註解需要匯入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/>
</beans>
此時我們通過一個案例來看一下
我們先搭建好環境
Spring檔案(這時候我們已經不需要在beans.xml檔案中裝配bean了)
<?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:component-scan base-package="com.luo"></context:component-scan>
<context:annotation-config/>
</beans>
通過在註解@Component標註在相應類上即可
通過測試可以得出