天天看點

spring IoC注解三、spring之IOC注解

三、spring之IOC注解

多spring配置檔案的使用(分子產品開發,每個子產品可能有自己的spring配置檔案)

spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解

(一)、搭建使用注解的方式 ioc注解

1. 有xml配置檔案(xml配置+注解組合使用)

第一步、要使用注解,需導入aop包

第二步、在配置檔案頭部加入context的schema

spring IoC注解三、spring之IOC注解

使用配置檔案使用

<context:component-scan>

<context:component-scan>

元件掃描,掃描裡邊有标注@Component, @Repository, @Service, @Controller的類變成元件,把這些類注冊到spring ioc容器中,等價于在配置檔案中使用

<bean id="" class="">
<context:component-scan base-package="org.lanqiao.entity"></context:component-scan>
           

把entity包下的有注解的類注冊到spring ioc容器中

第三步、使用注解

@Component 注解

@Repository, 專門注解到dao層

@Service, 專門注解到service層

@Controller 專門注解到controller層

@Lazy懶加載

@Scope(“singleton”)

@Scope(“prototype”)

2. 零配置(沒有xml檔案,全部用配置類)

(1)使用@Bean進行注冊(缺點:每一個類都要手動編寫注冊)

spring IoC注解三、spring之IOC注解
(2)不使用@Bean注解(缺點:)
           
spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解

(二)、使用其他注解 DI依賴注入注解

1.使用xml的屬性注入

spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解

2.使用注解來完成DI注入

spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解

@Autowired 等價于byType,按類型進行注入,優先查找類型,類型比對不成功或有多個,繼續按 名稱進行查找組合查找注入(優先根據名字)

  • @Autowired
  • @Qualifier(“studentDao2”)//byName
  • @Autowired(required=true) true:必須能注入值進來,預設的,在ioc容器找不到比對就會抛異常

    false:在ioc容器找不到的時候注入null進來,不會抛異常

  • @Primary 設定主要類,當ioc容器中調用@autowire自動注入時,因按類型比對注入,當出現多個同一類型的bean時,優先選擇設定了@primary的bean,而不會報錯
  • @Resource//byName按名稱查找 @Resource(name=“studentDao2”)
  • @Value 基本值的注入
    spring IoC注解三、spring之IOC注解

注解方式導入屬性檔案:

spring IoC注解三、spring之IOC注解

xml方式導入屬性檔案

spring IoC注解三、spring之IOC注解

使用@Value進行值的注入

spring IoC注解三、spring之IOC注解

@PostConstruct, 注解到方法上

@PreDestroy 注解到方法上

使用注解的地方:

spring注解 java注解 springmvc注解 springboot注解

注解和xml同時使用

使用配置類作為主導檔案

spring IoC注解三、spring之IOC注解
spring IoC注解三、spring之IOC注解

使用xml檔案作為主導配置檔案

spring IoC注解三、spring之IOC注解

總結:IOC和DI相比傳統的方式如何實作解耦的