Spring:如果未定义bean,如何忽略@Autowired属性

dim*_*902 12 spring

情况:我有一个带有@Autowired注释的属性的类:

public class MyClass {
    @Autowired
    protected MyAutoWiredBean myAutowiredBean;
}
Run Code Online (Sandbox Code Playgroud)

是否有可能将这个bean连接成可选的,即如果在某个配置文件中定义了这样的bean - 连接它,但是如果没有定义这样的bean - 只需继续工作而不抛出:

org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: protected MyAutoWiredBean...; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:      
No matching bean of type [com.mypackage.MyAutoWiredBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Run Code Online (Sandbox Code Playgroud)

Tom*_*icz 21

你有没有尝试过:

@Autowired(required=false)
Run Code Online (Sandbox Code Playgroud)

Javadoc:

声明是否需要带注释的依赖项.默认为true