spring5自动装配实例
所属分类 spring
浏览量 1472
配置类 Config
@Configuration
@ComponentScan
public abstract class Config{}
Pet接口
默认方法
public default void hello(){
System.out.println(this.toString()+",say hello,"+new Date());
}
Cat Dog Tiger 实现 Pet接口
scans.Cat
scans.a.Dog
scans.b.Tiger
@ComponentScan 不设置扫描路径 会扫描配置所在包及子包
@ComponentScan({"scans"}) 扫描 scans 包及子包
@Component
public class Zoo{
@Autowired
private Cat cat;
@Autowired
private Dog dog;
@Autowired
private Tiger tiger;
@Autowired
private Pet cat3;
org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'scans.Pet' available: expected single matching bean but found 3: cat,dog,tiger
使用 @Qualifier 消除歧义
@Autowired
@Qualifier("cat")
private Pet cat3;
@Autowired @Qualifier("cat")
或者
@Resource(name="cat")
private Pet cat3;
同时写上 也 ok
@Resource(name="cat")
@Autowired @Qualifier("cat")
注释 Dog 上的 @Component 注解
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'scans.a.Dog' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
可设置 required 为 false
@Autowired(required=false)
@Resource 注解无法实现类似功能
@Autowired(required=false) @Qualifier("catNotExist")
private Pet cat4;
@ComponentScan({"a.b.c","x.y.z"})
@ComponentScans 可 配置对个 @ComponentScan
@ComponentScans({@ComponentScan("a.b"),@ComponentScan("x.y")})
@ComponentScans({@ComponentScan({"a.b","x.y"})})
上一篇
下一篇
spring aop 内部方法调用拦截说明
spring aop cglib 代理类源码查看
Properties使用UTF8读取中文配置文件
eclipse异常断点设置
eclipse设置条件断点和异常断点
spring5属性及内嵌属性解析