79505601

Date: 2025-03-13 06:44:04
Score: 2
Natty:
Report link

There are basically 3 ways in spring to inject a dependency to the target class. You need to understand the difference first to understand what you need to achieve.

  1. Field Injection:

    @Service
    public class StudentService {
      @Autowired
      private StudentRepository studentRepo;
       // complete service code using studentRepo
    }
    

    Field injection can be achieved using Spring by adding the @Autowired annotation to a class field. And what does @Autowired do? @Autowired is an annotation provided by Spring that allows the automatic wiring of the dependency. When applied to a field, method, or constructor, Spring will try to find a suitable dependency of the required type and inject it into the target class.

  2. Setter Injection:

    @Service
    @Transactional
    public class UserService {
        private UserRepository userRepository;        
    
        @Autowired // Setter Injection
        public void setUserRepository(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        ...
    } 
    

    One more method to do Dependency Injection using Spring is by using setter methods to inject an instance of the dependency.

  3. Constructor Injection:

    @Service
    @Transactional
    public class StudentService {
        private final StudentRepository studentRepo;
    
         // Dependency being injected through constructor
        public StudentService(StudentRepository studentRepo) {
                 this.studentRepo = studentRepo;
        }
         ...
    }
    

    The final one is Constructor Injection. In OOP we create an object by calling its constructor. If the constructor expects all required dependencies as parameters, then we can be 100% sure that the class will never be instantiated without having its dependencies injected.

Now the confusing part for you is the @AllArgsConstructor annotation provided by the Lombok library. What this annotation does is that it simply creates a constructor of the class with all the available member fields of that class. So basically this annotation does the same thing what can be achieved by the constructor injection with a simple annotation. But remember the Field injection, Setter injection & Constructor injection are not the same & used on different scenarios. you can refer this link for more details - https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html#beans-constructor-vs-setter-injection

Reasons:
  • Blacklisted phrase (1): this link
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @Autowired
  • User mentioned (0): @Autowired
  • User mentioned (0): @Autowired
  • User mentioned (0): @AllArgsConstructor
  • Low reputation (1):
Posted by: Rudi009