Spring Boot @Autowired Example

1. Introduction

The @Autowired annotation is used to inject the bean automatically. The @Autowired annotation is used in Constructor injection, Setter injection, and Field injection.

Key Points:

1. @Autowired automatically injects dependencies specified in the Spring context into your components.

2. It can be used on variables, setters, and constructors for injection.

3. @Autowired uses type-based injection, where it matches the data type of beans for injecting the dependencies.

2. Implementation Steps

1. Define a service class that will act as a dependency.

2. Create a component class where this service will be injected.

3. Use the @Autowired annotation to inject the service class into the component.

4. Create a main application class that runs the Spring Boot application.

5. Implement the CommandLineRunner interface to execute some code after the application context is fully started.

3. Implementation Example

// Step 1: Define a service that will provide a message
@Component
public class GreetingService {
    public String greet() {
        return "Hello, World!";
    }
}

// Step 2: Create a consumer of the service that uses the greeting
@Component
public class GreetingApp {
    private final GreetingService greetingService;

    // Step 3: Use constructor injection to inject the greeting service
    @Autowired
    public GreetingApp(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    public void execute() {
        System.out.println(greetingService.greet());
    }
}

// Step 4: Create the main application class
@SpringBootApplication
public class AutowiredExampleApplication implements CommandLineRunner {

    private final GreetingApp greetingApp;

    // Constructor injection of the greeting application
    @Autowired
    public AutowiredExampleApplication(GreetingApp greetingApp) {
        this.greetingApp = greetingApp;
    }

    public static void main(String[] args) {
        SpringApplication.run(AutowiredExampleApplication.class, args);
    }

    // Step 5: Execute code using CommandLineRunner after the context is loaded
    @Override
    public void run(String... args) {
        greetingApp.execute();
    }
}

Output:

Hello, World!

Explanation:

1. @Component on the GreetingService class marks it as a Spring-managed bean.

2. The GreetingApp class is marked as a Spring @Component, making it eligible for dependency injection.

3. @Autowired on the constructor of GreetingApp tells Spring to inject a GreetingService bean at runtime.

4. AutowiredExampleApplication implements CommandLineRunner, providing a method run that is executed post-launch.

5. Within the run method, we invoke the execute method of GreetingApp, which calls the greet method of GreetingService.

6. The output is the result of these calls, which prints "Hello, World!" to the console.


Comments