Share on Google+Share on Google+

Excluding a bean from autowiring in spring.

In this tutorial you will learn how to exclude a bean from autowiring in spring.

Excluding a bean from autowiring

In this tuorial you will see how to exclude bean from autowiring. The autowire-candidate attribute is set in the <bean/> element and when it is set to false the container excludes that specific bean from autowiring.

package spring.exclude.autwiring;

import org.springframework.beans.factory.annotation.Autowired;

public class College {

  private Student student1;
  private String registration;
  private String year;

  public void setStudent1(Student student) {
    this.student1 = student;

  public String getRegistration() {
    return registration;

  public void setRegistration(String registration) {
    this.registration = registration;

  public String getYear() {
    return year;

  public void setYear(String year) {
    this.year = year;

  public String toString() {
    return "College [registration=" 
+ registration + ", Student="
        + student1 + ",year=" + year + "]";


package spring.exclude.autwiring;

public class Student {
  private String age;
  private String name;
  private String address;

  public String getAge() {
    return age;

  public void setAge(String age) {
    this.age = age;

  public String getName() {
    return name;

  public void setName(String name) { = name;

  public String getAddress() {
    return address;

  public void setAddress(String address) {
    this.address = address;

  public String toString() {
    return "Student [name=" + name + ", age=" + age +
",address=" + address


package spring.exclude.autwiring;

import org.springframework.beans.factory.BeanFactory;

public class AutowireMain {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
    College coll = (Collegebeanfactory.getBean("college5");


<beans xmlns=""
<!-- exclude auto-Wiring -->

<bean id="college5" 
class="spring.exclude.autwiring.College" autowire-candidate="false">
    <property name="registration" value="BL001" />
    <property name="year" value="2001" />

<bean id="student5" class="spring.exclude.autwiring.Student"  >
  <property name="address" value="Delhi" />
  <property name="age" value="22" />
  <property name="name" value="Raj" />

<!-- End -->


When you run this application it will display output as shown below:

College [registration=BL001, Student=null,year=2001]

Download this example code


Posted on: August 27, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.