Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: how to ignore @Autowired property if bean is not defined

Tags:

spring

Situation: I have I class with property annotated with @Autowired:

public class MyClass {
    @Autowired
    protected MyAutoWiredBean myAutowiredBean;
}

Is there any possibility to made wiring this bean optional, i.e. if such bean is defined in some configuration file - to wire it, but if such bean is not defined - just continue working without throwing:

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. 
like image 796
dim1902 Avatar asked Oct 07 '11 11:10

dim1902


People also ask

How do you Excluding a bean from being available for Autowiring?

You can exclude a bean from autowiring in Spring framework per-bean basis. If you are using Spring XML configuration then you can exclude a bean from autowiring by setting the autowire-candidate attribute of the <bean/> element to false.

How do you make Autowiring as non mandatory for a specific bean property?

If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.

Which exception is thrown if the Spring container does not find any bean for Autowiring?

A BeanFactory is basically the abstraction representing Spring's Inversion of Control container. It exposes beans internally and externally, to your application. When it cannot find or retrieve these beans, it throws a NoSuchBeanDefinitionException .

How do I turn off Autowire in Spring?

To fix it, you can disable this checking feature by setting the “required” attribute of @Autowired to false.


1 Answers

Have you tried:

@Autowired(required=false)

Javadoc:

Declares whether the annotated dependency is required. Defaults to true

like image 160
Tomasz Nurkiewicz Avatar answered Nov 12 '22 23:11

Tomasz Nurkiewicz