Spring Exclude Bean From Autowiring
This tutorial shows you how to exclude beans from autowiring. The <beans/> element has a autowire-candidate attribute which you can set to false to tell the container to make the bean unavailable for autowiring.
Beans
The @Autowired
annotation of the Person
bean makes the Job
bean eligible for autowiring.
package com.memorynotfound.spring.core.autowired;
import org.springframework.beans.factory.annotation.Autowired;
public class Person {
private String name;
private Job job;
public void setName(String name) {
this.name = name;
}
@Autowired
public void setJob(Job job) {
this.job = job;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", job=" + job +
'}';
}
}
The Job
bean will be autowired in the Person
bean.
package com.memorynotfound.spring.core.autowired;
public class Job {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Job{" +
"name='" + name + '\'' +
'}';
}
}
Exclude bean from Autowiring
You can exclude a bean from autowiring using the autowire-candidate attribute of the <beans/> element. This makes the bean unavailable to the spring container for autowiring.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="com.memorynotfound.spring.core.autowired.Job" autowire-candidate="false">
<property name="name" value="Java Developer"/>
</bean>
<bean class="com.memorynotfound.spring.core.autowired.Person">
<property name="name" value="John Doe"/>
</bean>
</beans>
Running The Application
package com.memorynotfound.spring.core.autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Run {
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");
Person person = context.getBean(Person.class);
System.out.println(person);
}
}
Output
This will throw a NoSuchBeanDefinitionException
exception because no bean definition was found.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorynotfound.spring.core.autowired.Job] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}