Sobes.tech
Middle

How can dependency injection be applied using Spring Bean?

sobes.tech AI

Answer from AI

Spring Boot supports Dependency Injection (DI) mainly in three ways:

  1. Field Injection:
    The most common and simple way. Using @Autowired on a field. Not recommended for production code due to testing and encapsulation issues.

    // Field Injection
    @Service
    public class MyService {
    
        @Autowired
        private MyDependency dependency;
    
        public void doSomething() {
            dependency.execute();
        }
    }
    
  2. Setter Injection:
    Using @Autowired on a setter method. Allows optional dependencies (if setter can be omitted) and easier testing.

    // Setter Injection
    @Service
    public class MyService {
    
        private MyDependency dependency;
    
        @Autowired
        public void setDependency(MyDependency dependency) {
            this.dependency = dependency;
        }
    
        public void doSomething() {
            dependency.execute();
        }
    }
    
  3. Constructor Injection:
    The most recommended way. Using @Autowired on the constructor. Ensures immutability of dependencies after object creation and clearly indicates required dependencies. In Spring Boot 2.x+, @Autowired on a single constructor can be omitted.

    // Constructor Injection
    @Service
    public class MyService {
    
        private final MyDependency dependency;
    
        // @Autowired is optional for a single constructor in Spring Boot 2.x+
        public MyService(MyDependency dependency) {
            this.dependency = dependency;
        }
    
        public void doSomething() {
            dependency.execute();
        }
    }
    

Spring container scans classes with annotations like @Component, @Service, @Repository, @Controller and creates Beans from them. When a Bean with @Autowired on a field, setter, or constructor detects a need for another dependency, the container searches for a suitable Bean by type and/or name and injects it. If multiple Beans match, @Qualifier can be used for clarification.

How can dependency injection be applied using Spring… - sobes.tech