SptingBoot的我的项目业务加强和测试
1.如果一个接口有两个实现类,并且都(@Component)都交给bean治理,当测试类从bean中获取(@AutoWired)这个接口对象时,会呈现什么问题?
package com.py.pj.commom.cache;
public interface Cache {
}
package com.py.pj.commom.cache;
import org.springframework.stereotype.Component;
@Component
public class SoftCache implements Cache{
}
package com.py.pj.commom.cache;
import org.springframework.stereotype.Component;
@Component
public class WeakCache implements Cache{
}
package com.py.pj.commom.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.py.pj.commom.cache.Cache;
@Component
public class SearchService {
private Cache cache;
public SearchService(Cache cache) {
this.cache = cache;
}
// 外界通过get取得spring容器注入的cache对象
public Cache getCache() {
return cache;
}
}
测试类
@SpringBootTest
public class TestCache {
@Autowired
@Qualifier("softCache")
private Cache cache;
@Test
void testCache() {
System.out.println(cache);
}
}
- 呈现相似谬误的起因:名为Cache的bean对象在默认的singleton作用域中有两个值softCache、weakCache。不晓得取哪一个造成的谬误。
- 有三种解决方案:
须要用到@Autowired和@Qualifier,@Qualifier需和@Autowired配合应用。
(1)间接在SearchService类中@Autowired给Cache注入值,并应用@Quailfier()抉择注入类型的属性,在这里咱们能够抉择softCache和weakCache其中一个。
@Autowired
@Qualifier("softCache")
private Cache cache;
public SearchService() {
}
(2)第二种是借助set办法和无参结构,给Cache注入为weakCache的值
public SearchService() {
}
// set这种方无参构造函数配合应用
@Autowired
@Qualifier("weakCache")
public void setCache(Cache cache) {
this.cache = cache;
}
(3)应用有参构造方法,把@Qualifier加在参数类型之前,并定义属性的类型。
// 独立应用
// @Autowired // 形容构造方法可省略
public SearchService(@Qualifier("softCache")Cache cache) {
this.cache = cache;
System.out.println(this.cache);
}
2.在下面应用到了@Autowired和@Qualifier,则它们的利用规定和作用是什么?
- Autowired:用于形容类中的属性或者办法(比方下面呈现的构造方法)。Spring框架在运行规定时候,如果有bean对象的办法或者属性应用@Autowired形容,则Spring框架会依据指定的规定为属性赋值(DI)。
- 其根本规定是:首先要检测容器中是否有与属性或办法参数类型相匹配的对象,如果有并且只有一个则间接注入。其次,如果检测到有多个,还会依照@Autowired形容的属性或办法参数名查找是否有名字匹配的对象,有则间接注入,没有则抛出异样。最初,如果咱们有明确要求,必须要注入类型为指定类型,名字为指定名字的对象还能够应用@Qualifier注解对其属性或参数进行形容(此注解必须配合@Autowired注解应用)。具体过程可参考图-18的设计进行自行尝试和实际。
发表回复