Guide to Spring @Autowired
Spring希望由@Autowired注解的依赖在某个依赖bean被构造时是可以访问的。如果框架不能解析这个用于wiring的bean,就会抛出异常并阻止Spring容器的启动:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.autowire.sample.FooDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
要避免这种情况的发生,一个bean可以这样选择性地指定:
public class FooService { @Autowired(required = false) private FooDAO dataAccessor; }