No "new" objects for Java Spring and how to convert legacy application to "Spring" concept - spring

I have just started learning Java Spring and the concept of Dependency Injection (DI) and Inversion of Control (IoC).
I learned that all objects whether it is singleton, prototype or request and sessions, are all retrieved from the container.
The container manages the dependencies between classes and the lifecycle/scope of the object.
The fundamental idea behind this is there are no "new" operators for application using Spring Framework as the backbone of the system. (Please correct me if I am wrong).
I wanted to modernize legacy applications coded without the Spring framework and manages the 3rd party libraries classes and injects them using Spring.
How should I approach this?

I learned that all objects whether it is singleton, prototype or request and sessions, are all retrieved from the container.
That is not quite right. Not all objects, but those you have the cotainer told to resolve, are retrieved from the container. In general you use the #Component annotation to mark which of your objects should the container know of. Besides #Component there are other annotations which do in principle the same, but allow a more finegrained semantics, e.g. #Repository annotation, which is at its base #Component and put #Target, #Retention, #Documented on top.
The container manages the dependencies between classes and the lifecycle/scope of the object.
Yes. The container does the wiring up for you, i.e. resolving dependencies annotated with #Ressource, #Autowired or #Inject depending on which annotation you prefer.
During the lifecycle there are possible events, which allow usage of lifecycle callbacks.
Also: You could determine the bean scope.
The fundamental idea behind this is there are no "new" operators for application using Spring Framework as the backbone of the system. (Please correct me if I am wrong).
The fundamental principle is, that you delegate the creation of objects of a certain kind to the container. Separation of creation and consumption of objects allows greater flexibility and in consequence better testability of your application.
Besides the "components" of your application, there are e.g. the typical containers like ArrayList or HashMap, upon which you use the new-operator as before.
I wanted to modernize legacy applications coded without the Spring framework and manages the 3rd party libraries classes and injects them using Spring.
How should I approach this?
From what was said above, it should be "simple":
1) Go through each class file and look for its dependencies
2) Refactor those out and put #Component on top of the class
Special case: 3rd party objects, where you do not have access to the source. Then you have to wrap its construction yourself into a factory e.g. with #Bean.
3) Add the missing dependencies via #Autowired (the spring specific annotation for marking dependencies)
4) Refactor components of the service layer with #Service annotationinstead of #Component.
5) Refactor the data access layer, instead of using #Component, you can use #Repository.
This should give you a base to work with.

Related

Why does spring use ioc and di?

I'm new to spring 5 and my question is why does spring use DI and IOC? I mean why do we have to write the beans in an XML (legacy) and then create it where we need it? Why don't we use one method instead that gives us that object, until we want to use this complex mechanism that happens in the spring container?
And another question is, does not reading XML slow down the program? Because we are reading from the hard disk anyway.
Note: It is true that we can use annotations, but for now I want to ask a question about reading from xml.
Spring IoC Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML) or Java Code or Java Annotations and Java POJO class. These objects are called Beans. Since the Controlling of Java objects and their lifecycle is not done by the developers, hence the name Inversion Of Control.
More on link HERE
As for your first part of the question.
why does spring use DI
To allow the developer to keep his code loose, and not entagle classes, it keeps your code clean.
In object oriented design, the amount of coupling refers to how much the design of one class depends on the design of another class. In other words, how often do changes in class A force related changes in class B? Tight coupling means the two classes often change together, loose coupling means they are mostly independent. In general, loose coupling is recommended because it's easier to test and maintain.
You may find this paper by Martin Fowler (PDF) helpful.
I mean why do we have to write the beans in an XML (legacy) and then create it where we need it
Note: We write the bean in XML and it is created when application starts when it looks at bean defintion, techinally you are never creating a bean, you are fetching only created bean from Spring Container(IOC) that Spring created for you when you started your application.
We are writing bean blueprint, or just bean, so that it can be constructed, placed in the Spring Container when the application starts, and then we have it at our disposal that we can fetch it using getBean method.
The whole point of "why", is because by default all beans are scoped as singleton, that means, when you fetch a bean, and do with it whatever you want, you do not worry about memory or anything, Spring takes care of the beans for you if they are scoped as a Singleton.
Second question:
And another question is, does not reading XML slow down the program? Because we are reading from the hard disk anyway.
There is no difference in performance between annotation or XML, it is just a different approach, I am not sure what you mean by "reading from hard disk", but one way or another you will have to configure your application, yes, many forums prefer to run away from XML, but in my honest opinion the only reason for that is because when you write a bad configuration in XML it is lot harder to find it compared to configuration in Java that will throw an exception.
XML, application.properties files require a redeployment of the application, while annotation and java configuration require recompilation of your project, so both of them have "flaws", but it is normal and quite understandable to me.
But in the end I believe that it is a matter of preference, I know personally quite a few people that combine annotations with XML configuration and they know lot more about Spring compared to me.
So in summary, it is pain to write beans and their configuration, same as you can write a class with methods without creating an interface for it since the result will be the same, but it will help you in the long run since you do not have to worry about memory or if you destroyed that bean or if you did not.
It would be nice that you read about
1.Lazy initialization of beans
2.Eager initialization of beans
3.Singleton scope of beans
4.Prototype scope of beans

Is Java Spring really better than straight up Java programming

I have read that dependency injection is good for testing, in that a class can be tested without its dependencies, but the question comes to my mind if Class A depends on Class B or C or any class, testing Class A independent of some class is yielding a test result of zero, not a failed or past test.
Class A was created to do something and if it is not fed anything whether using new key word or setting up the extra files in Spring, Class A won't do any work.
About the idea of making code modular, readable and maintainable: so business classes became cleaner, but all we did was shift confusion from dirty Java business classes to convoluted XML files and having to delete interfaces used to inject to our loosened objects.
In short, it seems we have to make edits and changes to a file somewhere,right?
Please feel free to put me in my place if my understanding is lacking, just a little irritated with learning Spring because I see the same amount of work just rearranged.
Dependency injection is good for unit testing because you can individually test each method without that method depending on anything else. That way each unit test can test exactly one method.
I would say that if the xml is what’s annoying you check out Spring boot. It’s based on a java configuration so no xml and it simplifies a lot of configuration for you based on your class path. When I first started spring I found the xml very daunting coming from a java background but the annotation based configuration and the auto configuring done by spring boot is extremely helpful for quickly getting applications working.
IMO biggest advantage of using the spring is dependency injection which makes your life easy. For example if you would like to create a new service with three dependencies, then you can create a class very easily using Spring. But without spring, you will end up writing different factory methods which will return you the instances you are looking for. This makes your code very verbose with static method calls. You may want to take a look at the code repositories before spring era.
Again if you would like to use Spring or not is your personal call based on project complexity. But it's other features/advantages cant be overlooked.
And XML files or Java configs are the ways of achieving spring configuration - where you would like to add your business logic is personal flavour. Only thing is you should be consistent all across your project.
I would suggest that you read Martin Fowler's great article on Inversion of Control and Dependency Injection to gain a better understanding of why frameworks like Spring can be really useful to solve a well known set of common dependency injection problems when writing software.
As others have mentioned, there is no obligation to use Spring; and whatever you can do with Spring, you can probably do it by other means like abstract factories, factory methods, or service locators.
If your project is small enough, then you probably wouldn't mind solving the dependency injection issues on your own using some design patterns like those mentioned above. However, depending on the size of your project, many would prefer to use a framework or a library that already packs a bunch of solutions to these recurrent head scratchers.
In regards to the advantages of dependency injection frameworks when doing unit testing is the idea that you don't need to test the dependencies of your class, but only your class.
For example, most likely your application has a layered design. It is very common to have a data access class or a repository that you use to retrieve data from a datasource. Logically, you also have a class where you use that DAO.
Evidently, you already wrote unit testing for your DAO, and therefore, when you're testing your business class (where the DAO is being used) you don't care about testing your DAO again.
Fortunately, since Spring requires some form of dependency injection for your DAO, this means your class must provide a constructor or a setter method through which we can inject that DAO into our business class, right?
Well, then during unit testing of your business class, you can conveniently use those injection points to inject your own fake DAO (i.e. a mock object). That way, you can focus on the testing of your business class and forget about retesting the DAO again.
Now compare this idea with other solutions you may have done on your own:
You inject the dependency directly by instantiating the DAO within your business class.
You use a static factory method within your code to gain access to the DAO.
You use a static method from a service locator within your code to gain access to the DAO.
None of these solutions would make your code easy to test because there is no simple manner to get in the way of choosing exactly what dependency I want injected into my business class while testing it (e.g. how do you change the static factory method to use a fake DAO for testing purposes?).
So, in Spring, using XML configuration or annotations, you can easily have different dependencies being injected into your service object based on a number of conditions. For example, you may have some configurations for testing that evidently would be different than those used in production. And if you have a staging environment, you may even have different XML configurations of dependencies for your application depending on whether it is running in production or integration environments.
This pluggability of dependencies is the key winning factor here in my opinion.
So, as I was saying, my suggestion to you is that you first expand your understanding of what problems Spring core (and in general all dependency injection frameworks) is trying to solve and why it matters, and that will give you a broader perspective and understanding of these problems in a way that you could to determine when it is a good idea to use Spring and when it is not.

Spring - dependency injection benefits

I'm a newbie to Spring Framework and of course first thing comes to mind about spring is dependency injection. Now i could be wrong since i just started learning about Spring framework (esp. about dependency injection) but i think that dependency injection of beans to said objects is not meant for transaction data. Since the bean definition is for example defined in the spring.xml (a blue print) it is not meant for transactional data but rather for static and small amount of data. I don't see that there's any way to inject thousands of transactional objects into another object using dynamic XML (created during runtime).
So did i get this right? If that is so what's the real benefit of dependency injection?
There are several benefits from using dependency injection containers rather than having components satisfy their own dependencies. Some of these benefits are:
Reduced Dependencies
Reduced Dependency Carrying
More Reusable Code
More Testable Code
More Readable Code
These benefits are explained in more detail here.
You are right, transactional data (eg: data that represents a table row) don't normally be injected declaratively. Spring DI (dependency injection) commonly use to handle collaboration between multiple classes.
Common examples I've seen is along with DAO (data access object) and MVC (model view controller) pattern. In enterprise environment it's common to have a project with dozens or hundreds of database tables -- hence dozens / hundreds of DAO classes which get injected into controller classes.
If you don't use DI, you need to conciously manage which DAO should be created first, and which DAO should be injected into which controller etc. (this is a nightmare)
Code refactoring is (should) be a common thing as well. Business requirement always changes constantly. Without DI one simple refactoring could result in a massive and tricky untangling of 'which class depends on what and where'
Of all the articles I've read about the dependency injection, this is by far the best.
If you are using Spring for DI, I would suggest you read about #primary annotation. Spring makes it even easier to choose the implementation you want(from multiple implementations) for a given service. This article is good.
Dependency Injection and Inversion of Control change the control flow adding to a specific component the responsibility to manage de dependency graph and manage how it will be connected. The result is a great decoupling between dependant and dependency, improving the code maintainability, application reliability, and testability.

Do annotations also couples code with framework like spring?

Extending spring based interfaces is discouraged as it unnecessarily couples the code with Spring. Does the same reasoning applies to annotations as well? We need to have them imported in the source code before using them.
I'll take the opposite viewpoint--of course using a Spring-specific annotation ties the class to Spring. I claim it's self-evident that importing and using Spring annotations ties the code to Spring (although you could trivially redefine those annotations for a non-Spring environment). The key for me is how deeply it's tied to Spring.
It's easier to check for, and process, annotations, than it is to restructure a class hierarchy or duplicate the functionality of a non-marker interface. Assuming you wanted to leave the annotations in, and could duplicate the logic behind the annotations, it'll be easier to do that (IMO) than to recreate whatever class/interface hierarchy implemented similar functionality.
The other key is the word "unnecessarily". I have yet to create a Spring application and need those classes outside of a Spring environment. When I have (generally for exposed APIs) it's been at the interface level. Note, however, that I knew from the onset that this exposure would exist and I planned accordingly.
Most would argue that this does not. While you've imported those annotations needed to ensure that Spring handles the request or wraps the transactions, you are not extending or implementing a specific class or interface.
Think about it this way, when you've annotated that class you're telling Spring to do various things based upon your configuration. Take out those annotations, and what you have is a POJO which just has some methods. It's a completely valid object without those annotations, it might not do what you wish it do (i.e. handle requests), but the code is still performing the same logic as it was with the annotations -- you are just now responsible for calling it appropriately.

Tomcat Spring WebApplicationContext

In the Spring framework reference I found this:
The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean method at all, and thus no dependency on Spring APIs at all.
but I have no idea to realize this.
After a lot of search I found this
avoid to use getBean in your application code, try to write a single class with one or more getBean() calls, this bootstrap class must be executed at the startup of your webapplication
is this a more recommended way?
Spring encourages you to use Inversion of Control, where the framework (e.g. Spring) injects dependencies into your objects, rather than your objects fetching things from the framework.

Resources