Understand the reason why Java spring uses constructor injection through an example
This article mainly introduces the reasons why spring uses constructor injection through examples. The example code in this article is very detailed, which has certain reference value for everyone's study or work. Friends in need can refer to it
1、 Foreword
The importance of spring framework to Java development is self-evident. Its core features are IOC (inversion of control) and AOP. The most commonly used IOC is IOC. We control the dependency of objects by spring by handing over the components to spring's IOC container to avoid excessive program coupling caused by hard coding.
2、 Three common injection methods
2.1 field injection
@Controller public class FooController { @Autowired //@Inject private FooService fooService; //简单的使用例子,下同 public List<Foo> listFoo() { return fooService.list(); } }
This injection method should be the most common injection method I have seen in development so far. The reason is simple:
The injection method is very simple: add the field to be injected and attach @ Autowired to complete it.
It makes the overall code concise and clear, and looks beautiful and generous.
2.2 constructor injection
@Controller public class FooController { private final FooService fooService; @Autowired public FooController(FooService fooService) { this.fooService = fooService; } //使用方式上同,略 }
In spring 4 This is the recommended injection method in version X. compared with the above field injection method, it is a little ugly. Especially when there are many injection dependencies (more than 5), it will be obvious that the code is very bloated
2.3 setter injection
@Controller public class FooController { private FooService fooService; //使用方式上同,略 @Autowired public void setFooService(FooService fooService) { this.fooService = fooService; } }
In spring 3 When X was first introduced, it was recommended to use injection, but the constructor injection parameters were too many and it was very cumbersome. In addition, the setter method can be used to allow the class to be reconfigured or re injected later.
3、 Benefits of constructor injection
This constructor injection method can ensure that the injected components are immutable and that the required dependencies are not empty. In addition, the dependencies injected by the constructor can always ensure a fully initialized state when returning the client (component) code
4、 Summary
Benefits of using constructor injection:
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.