Close

Spring - Defining injection point by using @Autowire annotation

[Last Updated: Dec 2, 2020]

The annotation @Autowired can be used to declare an injection point.

In other words, this annotation instructs the Spring container to find a registered bean of the same type as of the annotated type and perform dependency injection.

Example

@Autowired can be used at various places. Following example shows how to use it on a field.

package com.logicbig.example;

public class GreetingService {

  public String getGreeting(String name) {
      return "Hi there, " + name;
  }
}

Using @Autowired

package com.logicbig.example;

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

public class Greeter {
  @Autowired
  private GreetingService greetingService;

  public void showGreeting(String name) {
      System.out.println(greetingService.getGreeting(name));
  }
}

Defining beans and running the example application

package com.logicbig.example;

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

@Configuration
public class AppRunner {

  @Bean
  public GreetingService greetingService() {
      return new GreetingService();
  }

  @Bean
  public Greeter greeter() {
      return new Greeter();
  }

  public static void main(String... strings) {
      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppRunner.class);
      Greeter greeter = context.getBean(Greeter.class);
      greeter.showGreeting("Joe");
  }
}

Output

Hi there, Joe

@Autowire can also be used on setters , constructors and to any methods having multiple arguments.

Example Project

Dependencies and Technologies Used:

  • spring-context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Spring - @Autowire example Select All Download
  • spring-autowire-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Greeter.java

    See Also