@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; @Componentpublic 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;@Componentpublic 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;@Componentpublic class SearchServiceTests{  private SearchService searchService;  @Test  void testGetCache(){     System.out.println(searchService.getCache())  }}
能够尝试在SearchService中增加无参构造函数和setCache(Cache cache)办法,而后应用@Autowired形容setCache办法,并基于@Qualifier注解形容setCache办法参数。剖析进行注入过程。

总结(Summary)

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