Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Tutorials vs Real Life

I'm currently on the process of adding Spring and Hibernate to an existing application, but after reading lots of tutorials there are still a couple (aka a lot of things) that either seem strange to me or I'm missing something...

All the tutorials that I found are straight forward ones (like most tutorials should be), as seen on Example A, one controller to handle the requests (JSP or WS) and autowire the manager class to interact with the DB.

In my case this doesn't apply, since the application has a class to handle the requests, then it instantiates a handler class, which in turn creates a new class to handle something else that creates a new class to handle (....)* and then handles the the database connection as seen on Example B.

Spring diagram - Tutorial vs Real life

My question is how can I make my Business logic Class n "Springable", ie, able to make a Database Manager autowired inside of it?

From all the examples that I've seen, I've come up with these alternatives:

  1. Create the autowire to ALL the DbManager inside of the Controller, and then IoC to all the Business Classes until it reaches the Business Logic class n. This would follow with the Spring standards, but would imply the most code refactoring
  2. Transform ALL the Business Logic classes into beans
  3. Add SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); to the Business Logic class n and use the @Autowire to access the DbManager

Am I missing something or is there any other alternative?

like image 706
Gonçalo Cardoso Avatar asked Feb 02 '16 13:02

Gonçalo Cardoso


1 Answers

This is just my opinion, but you may be interested.

The basic philosophy of Spring, the fact that the creation and configuration of objects involved in the container, but not in the business objects, is known as IoC or Dependency Injection. Based on the configuration, the container creates and associates(injects) the objects with each other. This allows you to remove the code of the business-classes related to instantiation and configuration (this code can be quite complex). So your classes will become easier and cleaner, and can focus on the business-logic and nothing else.

I believe that business objects do not need to create each other. Let Spring do it. He does it perfectly.

Just mark your business logic classes, depend on its role, with one of stereotype: @Component, @Service, @Controller (meaning of stereotypes you can find here), and inject it with @Autowired. And if you need Database Manager in this classes, inject it same way.

So, my choice corresponds to point number two: "2. Transform ALL the Business Logic classes into beans..."

like image 113
Ken Bekov Avatar answered Oct 13 '22 13:10

Ken Bekov