关于spring:如何理解Spring中的Autowired

4次阅读

共计 1943 个字符,预计需要花费 5 分钟才能阅读完成。

@Autowired 简介

@Autowired 注解用于形容类中的属性,构造方法,set 办法,配置办法等,用于通知 Spring 框架依照指定规定为属性注入值 (DI)。

@Autowired 利用入门

基于如下 API 设计,进行代码实现进而剖析 @Autowired 利用剖析。

第一步:设计 Cache 接口

package com.cy.pj.common.cache;
public interface Cache {}

第二步: 设计 Cache 接口实现类 WeakCache,并交给 spring 治理。

package com.cy.pj.common.cache;
 
import org.springframework.stereotype.Component;
 
@Component
    
public class WeakCache implements Cache{}

第二步: 设计 Cache 接口实现类 SoftCache,并交给 spring 治理。

package com.cy.pj.common.cache;
 
@Component
public class SoftCache implements Cache{…}

第三步:设计单元测试类

package com.cy.pj.common.cache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
    
public class CacheTests {
    @Autowired
    @Qualifier("softCache")
    private Cache cache;
    
    @Test
    public void testCache() {System.out.println(cache);
    }
}

基于单元测试,剖析 @Autowired 利用(底层通过反射技术为属性赋值)。

阐明:Spring 框架在我的项目运行时如果发现由他治理的 Bean 对象中有应用 @Autowired 注解形容的属性,能够依照指定规定为属性赋值 (DI)。其根本规定是:首先要检测容器中是否有与属性类型相匹配的对象,如果有并且只有一个则间接注入。其次,如果检测到有多个,还会依照 @Autowired 形容的属性名查找是否有名字匹配的对象,有则间接注入,没有则抛出异样。最初,如果咱们有明确要求,必须要注入类型为指定类型,名字为指定名字的对象还能够应用 @Qualifier 注解对其属性或参数进行形容 (此注解必须配合 @Autowired 注解应用)。

@Autowired 利用进阶

@Autowired 注解在 Spring 治理的 Bean 中也能够形容其构造方法,set 办法,配置办法等,其规定仍旧是先匹配办法参数类型再匹配参数名,基于如下图的设计进行剖析和实现:

第一步:定义 SearchService 类并交给 Spring 治理

package com.cy.pj.common.service;
@Component
public class SearchService{

  private Cache cache;
  @Autowired
  public SearchService(@Qualifier("softCache")Cache cache){this.cache=cache;}
  public Cache getCache(){return this.cache;}
}

@Qualifier 能够形容构造方法参数,但不能够形容构造方法。

第二步:定义 SearchServiceTests 单元测试类。

package com.cy.pj.common.service;
@Component
public class SearchServiceTests{

  private SearchService searchService;
  @Test
  void testGetCache(){System.out.println(searchService.getCache())
  }
}

能够尝试在 SearchService 中增加无参构造函数和 setCache(Cache cache) 办法,而后应用 @Autowired 形容 setCache 办法,并基于 @Qualifier 注解形容 setCache 办法参数。剖析进行注入过程。

总结 (Summary)

本大节讲述了,在 Spring 框架中应用 @Autowired 注解形容类中属性、构造方法时的注入规定。而后深刻了解其注入过程。

正文完
 0