Spring注解装配

Spring 自动装配的主机有

@Autowired、@Intect、@Resource

@Autowired是byType的,

@Resource是byName的。我们一般用@Atutowired。

@Inject:等价于默认的@Autowired,只是没有required属性

但是如果在程序中有下面的例子怎么办呢?

public interface Family {
    .....
}
@Service('father')
public class Father implement Family {
    ......    
}
@Service('mother')
public class Mother implement Family {
    ......
}
@Controller
public class love {
    @Autowired
    private Family family;//①
    
}

  那你说①处注入进来的是father呢还是mother呢?如果这个时候运行spring容器的话就会报oSuchBeanDefinitionException这个异常 那怎么办呢? 就需要多加一个注解进行区分@Qualifler, 这个时候就可以这个样子区分了。

@Controller
public class love {
    @Autowired
    @Qyakufker('father')
    private Family family;
    
}

 当使用@Autowired在一个成员变量上面,如果没有这个变量的 bean,那么就会报NoSuchBeanDefinitionException这个异常,那可不可 就让这个对象是空的呢,当然可以。用@Autowired(required="false") 那么就会使这个对象是Null spring容器在启动的时候就不会报错误了

参考:

  [1]《Spring实战》,人民邮电出版社, Craig Walls

原文地址:https://www.cnblogs.com/happyflyingpig/p/8022852.html