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

时间:2011-10-07 11:40:36

标签: spring

情况:我的课堂上注明了@Autowired:

public class MyClass {
    @Autowired
    protected MyAutoWiredBean myAutowiredBean;
}

有没有可能将这个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. 

2 个答案:

答案 0 :(得分:19)

你试过了吗?

@Autowired(required=false)

Javadoc

  

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

答案 1 :(得分:5)