SpringBoot's Bean class three injection methods (with LomBok injection)
In Spring Boot, the injection methods of beans mainly include constructor injection, field injection, and Setter method injection. Each injection method has its own characteristics and applicable scenarios. In addition, Lombok provides a way to simplify dependency injection, which can reduce boilerplate code and improve development efficiency. The following is a detailed introduction to these injection methods, and the Lombok injection method is attached.
1. Constructor Injection
Usage scenario: Constructor injection is the preferred dependency injection method officially recommended by Spring, and is especially suitable for mandatory dependencies injection. It ensures that all necessary dependencies already exist when the object is created, and once the object is created, these dependencies cannot be changed again, thus ensuring the consistency and immutability of the object state. Constructor injection can also help solve the problem of circular dependencies, because Spring throws exceptions when detecting circular dependencies, forcing developers to solve this problem.
@Service public class MyService { private final MyRepository repository; @Autowired // Optional, can be omitted in Spring 4.3+ version public MyService(MyRepository repository) { = repository; } // ... }
A significant advantage of constructor injection is that it can be used in conjunction with the final keyword, making dependencies an immutable property, enhancing the security and readability of the code. Constructor injection is ideal for scenarios where you need to ensure that dependencies do not change throughout the life of the object.
2. Field Injection
Use scenario: Field injection is a simple and straightforward way to implement dependency injection by adding @Autowired annotation to the private fields of the class. The advantage of this approach is that the code is simple and easy to read, and is especially suitable for small projects or prototype development stages. However, field injection also has some potential risks, such as potentially causing null pointer exceptions, as it allows objects to be used without fully initialization. Additionally, field injection can raise issues with circular dependencies and is not conducive to unit testing, as mock implementations for dependencies cannot be easily provided.
@Service public class MyService { @Autowired private MyRepository repository; // ... }
Although field injection is very convenient in some cases, it is not a best practice, especially in large projects. Field injection should be avoided as much as possible and instead of safer and more reliable constructor injection or Setter method injection.
3. Setter method injection
Usage scenario: Setter method injection allows setting dependencies by calling Setter methods in a class, which are usually used for injection of non-mandatory dependencies. This approach provides greater flexibility as it allows reconfiguration or update dependencies after object creation. This is useful for scenarios where dependencies need to be adjusted dynamically, for example, changing certain behaviors based on user input or other external conditions during application runs. However, Setter method injection also has certain limitations, such as it may cause the object to be incomplete until all Setter methods are called.
@Service public class MyService { private MyRepository repository; @Autowired public void setRepository(MyRepository repository) { = repository; } // ... }
An important advantage of Setter method injection is that it supports multi-parameter dependency injection. When a class has multiple dependencies, using Setter method injection can make the code clearer and easier to understand. In addition, Setter method injection allows new dependencies to be added without modifying existing code, which is important for maintaining and extending existing systems.
4. Use Lombok for dependency injection
Use scenario: Lombok is a popular Java library designed to reduce boilerplate code and improve development efficiency. It can automatically generate common getters, setters, constructors and other methods through annotations, thereby simplifying the process of dependency injection. Lombok supports two main dependency injection methods: constructor injection and Setter method injection. Using Lombok can significantly reduce the effort to write duplicate code manually, making the code more concise and clear.
Constructor injection
Lombok provides the @RequiredArgsConstructor annotation, which can generate a constructor for all final or fields with @NonNull tags but uninitialized. This constructor will automatically bring the @Autowired annotation to implement dependency injection. This approach not only reduces the amount of code, but also maintains the security and immutability characteristics of constructor injection.
@Service @RequiredArgsConstructor(onConstructor_ = @__(@Autowired)) // Suitable for Spring 4.3 and below// For Spring 4.3 and above, you can use @RequiredArgsConstructor directlypublic class MyService { private final MyRepository repository; }
Setter method injection
Lombok also supports automatic generation of Setter methods through @Setter annotations, and can automatically add @Autowired annotations on the generated Setter methods. This approach is especially suitable for scenarios where dependencies need to be adjusted dynamically after object creation. However, it should be noted that Setter method injection may risk the object being in an incomplete state and should be used with caution.
@Service @Setter(onMethod_ = @Autowired) public class MyService { private MyRepository repository; }
Summarize
To sum up, constructor injection, field injection and Setter method injection have their own advantages and disadvantages and are suitable for different scenarios. Constructor injection is preferred for its security, immutability, and efficient handling of circular dependencies; field injection is simple but risky and is more suitable for rapid development and small projects; Setter method injection provides additional flexibility for applications that require dynamic adjustment of dependencies. The introduction of Lombok further simplifies the process of dependency injection, reduces boilerplate code, and improves development efficiency. Developers should reasonably choose the most suitable injection method based on the specific needs of the project and personal preferences. It is worth noting that with the development of Spring frameworks, officials are increasingly inclined to recommend constructor injection because it can better meet the best practices of modern software development.
The above is the detailed explanation of the three injection methods of SpringBoot's Bean class. For more information about SpringBoot Bean class injection methods, please pay attention to my other related articles!