Spring Bean Autowire ‘byName’ Example

In Spring Framework, autowiring by name is a feature that allows developers to inject dependencies into a bean by matching the property name with the name of the target bean. This is achieved using the @Autowired annotation (Java Configuration) along with the byName attribute (XML Configuration).

For dependency injection in Spring framework:

1. What is Autowiring By Name?

When autowiring by name, Spring searches for a bean whose name matches the name of the property being autowired.

  • If a match is found, Spring injects that bean into the property.
  • If no matching bean is found, Spring throws NoUniqueBeanDefinitionException unless the property is marked as optional with @Autowired (required = false).

Spring will inject a bean named “circle” into the field in the following example.

public class ShapeService {

  @Autowired
  private Shape circle;

}

2. Autowiring By Name with Examples

Suppose we have a ShapeService class that performs some action on the Shape object whatever is injected into it.

public class ShapeService {

  @Autowired
  private Shape shape;

  public void drawShape() {
    if (shape != null) {
      shape.draw();
    } else {
      System.out.println("No shape set.");
    }
  }
}

The Shape is an abstract type that can have multiple implementations.

public abstract class Shape {
  abstract void draw();
}

Now imagine we created two such implementations of Shape as follows:

public class Square extends Shape {
  @Override
  void draw() {
    System.out.println("Drawing the Square");
  }
}

public class Circle extends Shape {
  @Override
  void draw() {
    System.out.println("Drawing the Circle");
  }
}

To create the beans from the above classes, we create the BeanConfig class. Here we can define all the beans that must be present in the application context.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {

  @Bean
  Square square() {
    return new Square();
  }

  @Bean
  Circle circle() {
    return new Circle();
  }

  @Bean
  ShapeService shapeService() {
    return new ShapeService();
  }
}

To run the program, we use the AnnotationConfigApplicationContext to load the beans and access any of the bean methods.

public class AutowiredByTypeExample {

  public static void main(String[] args) {

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);

    ShapeService shapeService = context.getBean(ShapeService.class);
    shapeService.drawShape();
  }
}

2.1. Bean Exists with the Specified Name

Let’s change the ShapeService and rename the property to circle.

public class ShapeService {

  @Autowired
  private Shape circle;

  public void drawShape() {
    if (circle != null) {
      circle.draw();
    } else {
      System.out.println("No shape set.");
    }
  }
}

When we run the program, we get the expected message :

Drawing the Circle

Similarly, when we rename the variable to square then also we get the bean injected successfully.

public class ShapeService {

  @Autowired
  private Shape square;

  public void drawShape() {
    if (square != null) {
      square.draw();
    } else {
      System.out.println("No shape set.");
    }
  }
}

The program output:

Drawing the Square

2.2. When No Bean is Present with Matching Name

When no bean matching the field name is present in the context then autowiring byType is applied and Spring searches the beans with the matching types.

When autowiring by type, Spring looks for a bean of the same type as the property being autowired.

  • if there is exactly one bean of the property type in the container, it injects that bean.
  • If there are multiple candidates of the same type, Spring throws NoUniqueBeanDefinitionException because it cannot determine which one to inject.
  • In cases where no matching bean is found:
    • Spring throws NoSuchBeanDefinitionException if the dependency is required.
    • The field is unset (remains null) if the dependency is optional.

3. Conclusion

Autowiring by name in Spring is a convenient way to inject dependencies by matching the property name with the name of the target bean. It simplifies configuration and reduces the need for explicit wiring.

However, be cautious of conflicts when multiple beans of the same name exist.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode