In an MVC application, where will dependency injection be done?

When using Spring and Spring MVC, where are dependency injection (DI)?

An example is if you have a controller and many actions in the controller.

You would do:

@RequestMapping("/blah") public String SomeAction() { ApplicationContext ctx = new AnnotationConfigApplicationContext(); MyService myService = ctx.getBean("myService"); // do something here return "someView"; } 

Would this be a best practice approach? Or is this their best way?

+4
source share
3 answers

The whole idea of โ€‹โ€‹Injection Dependency is not to let your classes know or care about how they get the objects they depend on. When injected, these dependencies should simply โ€œappearโ€ without any request (hence the inversion of control). When using ApplicationContext#getBean(String) you are still requesting a dependency (a la Service Locator), and this is not an inverse of the control (even if this makes it easy to change the implementation).

So, instead, you should make MyController a Spring a managed bean and insert a MyService using either installation or constructor-based installation.

 public class MyController { private MyService myService; public MyController(MyService aService) { // constructor based injection this.myService = aService; } public void setMyService(MySerice aService) { // setter based injection this.myService = aService; } @Autowired public void setMyService(MyService aService) { // autowired by Spring this.myService = aService; } @RequestMapping("/blah") public String someAction() { // do something here myService.foo(); return "someView"; } } 

And configure Spring to connect.

+10
source

Do not use getbean, which loses the goal of doing DI. Use @Autowired instead. DI is intended for use in a multi-level system, such as view, service, DAO , so that each layer is independent of each other.

+2
source

As a compliment to the Pascal post, Martin Fowler: Requires inversion of control containers and dependency injection pattern .

And as a comet said, you need to use the @Autowire annotation for this. In addition to this, Spring supports attachments based on name and type. I suggest you read about it.

+1
source

Source: https://habr.com/ru/post/1299398/


All Articles