Spring-02-IOC相關注解
阿新 • • 發佈:2021-10-10
註解驅動
什麼是註解驅動
註解驅動開發,在Spring工程中使用註解的形式替代XML配置,將繁雜的Spring配置檔案從工程中徹底消除掉,簡化書寫。
註解驅動弊端
可能會將原先很簡單的書寫,變得更加複雜,比如XML中配置第三方資源是很方便的,但使用註解驅動無法在第三方開發的資源中進行編輯,因此會增大開發工作量;
什麼時候使用XML配置,什麼時候使用註解開發
- 實際開發中如果我們自己定義的類想要被IOC容器管理,那麼一般使用註解開發
- 如果是第三方提供的類,比如Druid連線池物件,那麼建議使用XML配置
Bean常用註解
型別
類註解
位置
類的定義上方
作用
設定該類為Spring管理的bean
名稱
- @Component——設定該類為spring管理的bean
- @Controller——控制層註解
- @Service——服務層註解
- @Repository——持久層註解
- Configuration——配置類註解
以上註解都有value屬性,用於定義bean的id,它們相當於XML中的bean標籤
IOC註解配合XML開發流程說明
步驟
- 引入Spring核心依賴;
- 定義需要被IOC容器管理的類;使用Bean常用註解
- 在XML配置檔案中開啟註解掃描功能
- 使用Spring提供的工廠類載入xml檔案,初始化IOC容器
- 從IOC容器獲取bean物件,完成業務開發
引入Spring核心依賴;
<dependencies> <!--引入Spring核心--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--引入單元測試--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>
定義需要被IOC容器管理的類;使用Bean常用註解
介面
package com.learn.service; public interface UserService { void add(); String getName(String data); }
實現類
這裡對實現類添加了@Service註解
package com.learn.service.impl; import com.learn.service.UserService; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl implements UserService { @Override public void add() { System.out.println("add run..."); } @Override public String getName(String data) { System.out.println("getName:" + data); return data; } }
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 掃描com.heima下的一切資源(包路徑無限遞迴掃描),滿足spring註解,那麼就通過發射建立bena物件,然後加入ioc容器 --> <context:component-scan base-package="com.learn" /> </beans>
使用Spring提供的工廠類載入xml檔案,初始化IOC容器
從IOC容器獲取bean物件,完成業務開發
package com.learn; import com.learn.pojo.Student; import com.learn.pojo.User; import com.learn.service.UserService; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { @Test public void test04(){ ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = ctx.getBean("userService", UserService.class); userService.add(); } }
效果