How does dependency injection work in Spring? - java

I want to know how spring does dependency injection. I want the low level logic used.
Updates:
I want to know how the object references are injected to the constructors or setter methods, is it through Reflection or some byte code level.

Java components / classes should be as independent as possible of other Java classes. This increases the possibility to reuse these classes and to test them independently of other classes(Unit Testing). To decouple Java components from other Java components the dependency to a certain other class should get injected into them rather that the class itself creates / finds this object.
Class A has a dependency to class B if class A uses class B as a variable.
If dependency injection is used then the class B is given to class A via the constructor of the class A - this is then called construction injection; or via a setter - this is then called setter injection
The general concept of dependency injection is called Inversion of Control. A class should not configure itself but should be configured from outside.
A design based on independent classes / components increases the re-usability and possibility to test the software. For example if a class A expects a Dao (Data Access Object) for receiving the data from a database you can easily create another test object which mocks the database connection and inject this object into A to test A without having an actual database connection.
A software design based on dependency injection is possible with standard Java.
Spring just adds some simplifications in using dependency injection by providing a standard way of providing the configuration and by managing the reference to the created objects.
For more read this
Edit1:
When Spring initializes its context it creates all the beans defined eager in Spring application context.xml file.
Now suppose your Bean A has dependency of B then the Obj of B is already with Spring as it has been created successfully while Spring initialization. Then Spring will search for setter method in class A and will set B's Obj there.
Edit2:
Please read 5.4.1 Setter Injection

Configuration of dependencies are read from XML, annotations or Java DSL (JavaConfig). Then Spring DI engine wires the dependencies based on the metadata from the configuration using the Java reflection API.

Related

Do I need to create service interface for services in Spring Boot? [duplicate]

"Dependency Injection" and "Inversion of Control" are often mentioned as the primary advantages of using the Spring framework for developing Web frameworks
Could anyone explain what it is in very simple terms with an example if possible?
Spring helps in the creation of loosely coupled applications because of Dependency Injection.
In Spring, objects define their associations (dependencies) and do not worry about how they will get those dependencies. It is the responsibility of Spring to provide the required dependencies for creating objects.
For example: Suppose we have an object Employee and it has a dependency on object Address. We would define a bean corresponding to Employee that will define its dependency on object Address.
When Spring tries to create an Employee object, it will see that Employee has a dependency on Address, so it will first create the Address object (dependent object) and then inject it into the Employee object.
Inversion of Control (IoC) and Dependency Injection (DI) are used interchangeably. IoC is achieved through DI. DI is the process of providing the dependencies and IoC is the end result of DI. (Note: DI is not the only way to achieve IoC. There are other ways as well.)
By DI, the responsibility of creating objects is shifted from our application code to the Spring container; this phenomenon is called IoC.
Dependency Injection can be done by setter injection or constructor injection.
I shall write down my simple understanding of this two terms: (For quick understanding just read examples)
Dependency Injection(DI):
Dependency injection generally means passing a dependent object as a parameter to a method, rather than having the method create the dependent object.
What it means in practice is that the method does not have a direct dependency on a particular implementation; any implementation that meets the requirements can be passed as a parameter.
With this implementation of objects defines their dependencies. And spring makes it available. This leads to loosely coupled application development.
Quick Example:EMPLOYEE OBJECT WHEN CREATED,IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT (if address is defines as dependency by Employee object)*.
Inversion of Control(IoC) Container:
This is common characteristic of frameworks, IoC manages java objects - from instantiation to destruction through its BeanFactory. - Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean's scope, lifecycle events, and any AOP features for which it has been configured and coded.QUICK EXAMPLE:Inversion of Control is about getting freedom, more flexibility, and less dependency. When you are using a desktop computer, you are slaved (or say, controlled). You have to sit before a screen and look at it. Using keyboard to type and using mouse to navigate. And a bad written software can slave you even more. If you replaced your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of computer controlling it. By implementing Inversion of Control, a software/object consumer get more controls/options over the software/objects, instead of being controlled or having less options. Inversion of control as a design guideline serves the following purposes:- There is a decoupling of the execution of a certain task from implementation.- Every module can focus on what it is designed for.- Modules make no assumptions about what other systems do but rely on their contracts.- Replacing modules has no side effect on other modules
I will keep things abstract here, you can visit following links for detail understanding of the topic.
A good read with example
Detailed explanation
In Spring Objects are loosely coupled i.e., each class is independent of each other so that everything can be tested individually. But when using those classes, a class may be dependent on other classes which need to be instantiated first.
So, we tell spring that class A is dependent on class B. So, when creating bean(like class) for class A, it instantiates class B prior to that of class A and injects that in class A using setter or constructor DI methods. I.e., we are telling spring the dependency at run-time. This is DI.
As, we are assigning the responsibility of creating objects(beans), maintaining them and their aggregations to Spring instead of hard-coding it, we call it Inversion Of Control(IOC).
Inversion of control-
It means giving the control of creating and instantiating the spring beans to the Spring IOC container and the only work the developer does is configuring the beans in the spring xml file.
Dependency injection-
Consider a class Employee
class Employee {
private int id;
private String name;
private Address address;
Employee() {
id = 10;
name="name";
address = new Address();
}
}
and consider class Address
class Address {
private String street;
private String city;
Address() {
street="test";
city="test1";
}
}
In the above code the address class values will be set only when the Employee class is instantiated, which is dependency of Address class on Employee class. And spring solves this problem using Dependency Injection concept by providing two ways to inject this dependency.
Setter injection
Setter method in Employee class which takes a reference of Address class
public void setAddress(Address addr) {
this.address = addr;
}
Constructor injection
Constructor in Employee class which accepts Address
Employee(Address addr) {
this.address = addr;
}
In this way the Address class values can be set independently using either setter/constructor injection.
Inversion Of Control (IOC):
IoC is a design pattern that describes inverting the flow of control in a system, so execution flow is not controlled by a central piece of code. This means that components should only depend on abstractions of other components and are not be responsible for handling the creation of dependent objects. Instead, object instances are supplied at runtime by an IoC container through Dependency Injection (DI).
IoC enables better software design that facilitates reuse, loose coupling, and easy testing of software components.
Dependency Injection (DI):
DI is a technique for passing dependencies into an object’s constructor. If the object has been loaded from the container, then its dependencies will be automatically supplied by the container. This allows you to consume a dependency without having to manually create an instance. This reduces coupling and gives you greater control over the lifetime of object instances.
click to view more
Spring: Spring is “Inversion of Control” container for the Java Platform.
Inversion of Control (IoC): Inversion of Control (IoC) is an object-oriented programing practice whereby the object coupling is bounded at runtime by an "assembler" object and are typically not knowable at compile time using static analysis.
Dependency Injection (DI): "Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time." -wiki.
In simple terms..
IOC(Inversion of Control) is a concept that means: Instead of creating objects with the new operator,let the container do it for you.
DI(Dependency injection) is way to inject the dependency of a framework component by the following ways of spring:
Contructor injection
Setter/Getter injection
field injection
Inversion of Control is a generic design principle of software architecture that assists in creating reusable, modular software frameworks that are easy to maintain.
It is a design principle in which the Flow of Control is "received" from the generic-written library or reusable code.
To understand it better, lets see how we used to code in our earlier days of coding. In procedural/traditional languages, the business logic generally controls the flow of the application and "Calls" the generic or reusable code/functions. For example, in a simple Console application, my flow of control is controlled by my program's instructions, that may include the calls to some general reusable functions.
print ("Please enter your name:");
scan (&name);
print ("Please enter your DOB:");
scan (&dob);
//More print and scan statements
<Do Something Interesting>
//Call a Library function to find the age (common code)
print Age
In Contrast, with IoC, the Frameworks are the reusable code that "Calls" the business logic.
For example, in a windows based system, a framework will already be available to create UI elements like buttons, menus, windows and dialog boxes. When I write the business logic of my application, it would be framework's events that will call my business logic code (when an event is fired) and NOT the opposite.
Although, the framework's code is not aware of my business logic, it will still know how to call my code. This is achieved using events/delegates, callbacks etc. Here the Control of flow is "Inverted".
So, instead of depending the flow of control on statically bound objects, the flow depends upon the overall object graph and the relations between different objects.
Dependency Injection is a design pattern that implements IoC principle for resolving dependencies of objects.
In simpler words, when you are trying to write code, you will be creating and using different classes. One class (Class A) may use other classes (Class B and/or D). So, Class B and D are dependencies of class A.
A simple analogy will be a class Car. A car might depend on other classes like Engine, Tyres and more.
Dependency Injection suggests that instead of the Dependent classes (Class Car here) creating its dependencies (Class Engine and class Tyre), class should be injected with the concrete instance of the dependency.
Lets understand with a more practical example. Consider that you are writing your own TextEditor. Among other things, you can have a spellchecker that provides the user with a facility to check the typos in his text. A simple implementation of such a code can be:
Class TextEditor
{
//Lot of rocket science to create the Editor goes here
EnglishSpellChecker objSpellCheck;
String text;
public void TextEditor()
{
objSpellCheck = new EnglishSpellChecker();
}
public ArrayList <typos> CheckSpellings()
{
//return Typos;
}
}
At first sight, all looks rosy. The user will write some text. The developer will capture the text and call the CheckSpellings function and will find a list of Typos that he will show to the User.
Everything seems to work great until one fine day when one user starts writing French in the Editor.
To provide the support for more languages, we need to have more SpellCheckers. Probably French, German, Spanish etc.
Here, we have created a tightly-coupled code with "English"SpellChecker being tightly coupled with our TextEditor class, which means our TextEditor class is dependent on the EnglishSpellChecker or in other words EnglishSpellCheker is the dependency for TextEditor. We need to remove this dependency. Further, Our Text Editor needs a way to hold the concrete reference of any Spell Checker based on developer's discretion at run time.
So, as we saw in the introduction of DI, it suggests that the class should be injected with its dependencies. So, it should be the calling code's responsibility to inject all the dependencies to the called class/code. So we can restructure our code as
interface ISpellChecker
{
Arraylist<typos> CheckSpelling(string Text);
}
Class EnglishSpellChecker : ISpellChecker
{
public override Arraylist<typos> CheckSpelling(string Text)
{
//All Magic goes here.
}
}
Class FrenchSpellChecker : ISpellChecker
{
public override Arraylist<typos> CheckSpelling(string Text)
{
//All Magic goes here.
}
}
In our example, the TextEditor class should receive the concrete instance of ISpellChecker type.
Now, the dependency can be injected in Constructor, a Public Property or a method.
Lets try to change our class using Constructor DI. The changed TextEditor class will look something like:
Class TextEditor
{
ISpellChecker objSpellChecker;
string Text;
public void TextEditor(ISpellChecker objSC)
{
objSpellChecker = objSC;
}
public ArrayList <typos> CheckSpellings()
{
return objSpellChecker.CheckSpelling();
}
}
So that the calling code, while creating the text editor can inject the appropriate SpellChecker Type to the instance of the TextEditor.
You can read the complete article here
IOC is technique where you let someone else to create the object for you.
And the someone else in case of spring is IOC container.
Dependency Injection is a technique where one object supplies the dependency of another object.
IOC stands for inversion of control and is a higher level concept that states that we invert the control of the creation of objects from the caller to the callee.
Without inversion of control, you are in charge of the creation of objects. In an inversion of control scenario a framework is in charge to create instances of a class.
Dependency injection is the method through which we can achieve inversion of control. In order for us to leave the control up to the framework or job we declare dependencies and the IOC container injects those dependencies in our class (i.e. the framework creates an instance for us and provides that to our class).
Now what are the advantages of this?
First of all the classes and their lifecycle will be managed by Spring. Spring completely manages the process from creation to destruction.
Secondly, you will get reduced coupling between classes. A class is not tightly coupled with an implementation of another class. If an implementation changes, or if you want to change the implementation of the injected interface you can do so easily without needing to change all the instances in your code base by hand.
Third, there is an increased cohesion between classes. High cohesion means keeping classes that are associated with one another together. Because we are injecting interfaces in other classes it is clear which classes are necessary for the calling class to operate.
Fourth, there is increased testability. Because we are using interfaces in the constructor we can easily swap out the implementation with a mock implementation
fifth, the use of JDK dynamic proxy to proxy objects. the JDK dynamic proxy requires interfaces to be used which is true, because we are injecting these interfaces. This proxy can then be used for Spring AOP, transaction handling, Spring data, Spring security and more
The traditional way of getting address instance in Employee would be by creating a new instance of Address class.Spring creates all dependent object ton us hence we need not to worry about object.
So in Spring we just depend on the spring container which provide us with the dependency object.
The Spring framework can be considered as a collection of sub-frameworks, also referred to as layers, such as Spring AOP, Spring ORM, Spring Web Flow, and Spring Web MVC. You can use any of these modules separately while constructing a Web application. The modules may also be grouped together to provide better functionalities in a web application.
Prior to penetrating down to Spring to container do remember that Spring provides two types of Containers namely as follows:
BeanFactory Container
ApplicationContext Container
The features of the Spring framework such as IoC, AOP, and transaction management, make it unique among the list of frameworks. Some of the most important features of the Spring framework are as follows:
IoC container
Data Access Framework
Spring MVC
Transaction Management
Spring Web Services
JDBC abstraction layer
Spring TestContext framework
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.

initialize an instance without any field in spring

I am trying to apply ioc into a school project. I have an abstract class Application without any field
public abstract class Application {
abstract public void execute(ArrayList<String> args, OutputStream outputStream, InputStream inputStream) throws IOException;
}
And I will call the concrete class that extends Application by
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Application app = (Application)context.getBean(appName);
My questions are:
Is it a bad practice to initialise a bean without any field (or all the fields are constants) using Spring?
As there is no dependency to other classes in Application, are we still consider this as a dependency injection or IOC? If no, what is the difference between this and a normal factory pattern? It seems that what Spring does here is simply matching the class and initializing it.
UPDATE
Here is the code snippet of the class where the instance of Application is needed.
String appName = argument.get(0);
Application app = ApplicationFactory.getApplication(appName);
ArrayList<String> appArgs
= new ArrayList<String>(argument.subList(1, argument.size()));
app.execute(appArgs, outputStream, inputStream);
Further questions:
in my code the class X will call the instance of Application by specifying a concrete application class name. In this case, it is still not possible for Spring to inject the dependency to Application, right? As what I need is a concrete class but not Application itself.
if Application does have fields but these fields are initialsed somewhere higher than X (X receives them as inputs and passes them to Application), can I use DI in this case?
Is it a bad practice to initialise a bean without any field (or all the fields are constants) using Spring?
No, its totally fine. Its true that you won't be able to "take advantage" of the automatic dependency injection mechanisms provided by spring (because obviously there are no dependencies in the class Application in your example), however spring can still:
Make sure that the Application as a singleton "obeys" the rule of being a single instance in the whole application context. For "manually" maintaining singletons you need to write code. Spring does it for you.
Manages the lifecycle of the object. Example, Spring has "postConstruct"/"preDestroy" methods that can can be run in the appropriate time and make example any custom code of the class Application.
If this class does some heavy-lifting (even without spring) than it can make sense to define it "lazy" so that the initialization of this instance will actually be done upon the first request to it.
Sometimes you/or spring itself will create a proxy of this class in runtime (for many different reasons, for example this aforementioned lazy functionality, but there are also other use cases). This is something that spring can do for you only if it manages the Application and not if its defined outside the spring.
Ok, you don't have dependencies in the application, This means that this Application class has some useful methods (at least on method, like public void foo() for
simplicity). But this in turn means that there is some class (lets call it X) that calls this method. So this class has an instance of Application as a dependency. So now the real question is who manages this class X. Probably it makes sense to manage it in Spring as well, and then you will benefit of the Dependency Injection mechanisms in this class X only because Application is also managed by Spring. In general Spring can inject dependencies only if these dependencies are managed by Spring.
I know, this last paragraph may sound vague given the use case you've presented, but you've got a point, for example in real application people make an initial bootstrapping in very certain places. Usually also people use spring boot that kind of encapsulates this kind of things for you.
As there is no dependency to other classes in Application, are we still consider this as a dependency injection or IOC? If no, what is the difference between this and a normal factory pattern? It seems that what Spring does here is simply matching the class and initializing it.
So as you see, the concept of DI container goes far beyond of what the factory pattern has to offer. In short, factory pattern only specifies the way to create the objects. Spring on the other hand, not only creates the objects but also manages them.
First, I very strongly suggest that you use Spring Boot instead of manually manipulating Spring at a low level like this.
It's perfectly ordinary to use beans that don't have their own fields for settings, but this is usually so that other beans can have pluggable strategies or providers and you can define in your application setup which to use.
If your Application class doesn't need anything else, then there really is not much advantage to Spring. Most real-world programs get complicated soon, however, and that's where it becomes useful.
Finally, you should almost never pass ArrayList as a parameter; use List instead. In the code you showed, however, if you have String[] args, you couldn't say app.execute(Arrays.asList(args), System.out).

Spring's AutowiredAnnotationBeanPostProcessor and constructor injection

Everybody knows that #Autowired(#Inject etc) annotation is processed by AutowiredAnnotationBeanPostProcessor. It parses and set fields and setters annotated with #Autowired but what about constructors? This is bean PostProcessor, that means that it is called after bean was already created, but constructors can also be marked as #Autowired, so how such beans are created?
Good question. For clarification's sake, to re-word it:
How does Spring provide the capability to do dependency injection on
constructor parameters when it seems like dependencies are injected
only after the bean is created?!
If you look at the AutowiredAnnotationBeanPostProcessor you'll find that there is a method called #determineCandidateConstructors that doesn't get called anywhere from inside that class itself.
The reason it's not called there is because it's referenced in the AbstractAutowireCapableBeanFactory; a class that's used for the actual creation/instantion of the bean!
I would imagine Juergen and the Spring guys decided it made architectural sense to put the #determineCandidateConstructors in the AutowiredAnnotationBeanPostProcessor class because it fits in with the concept function of the real purpose of Autowire-ing an injected dependency.
FYI, these concepts of field #Autowire vs. constructor #Autowire is so tightly tied together, that there is a whole discussion in the Spring DI world on whether to use constructor vs. dependency injection. See the section entitled Constructor-based or setter-based DI of this article, Oliver Gierke's comment (i.e. head of Spring Data project), and google for more information.

Role of new keyword in Spring Framework

In the Spring Framework, it seems like beans are the preferred way of creating objects to use in business logic.
[Dependency injection] is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.
So from my simple understanding, the difference is something like this:
// Plain ol' Java
Foo f = new Foo();
// Using beans in Spring Framework
Foo f = FooFactory.get();
Is it an oversimplification to say that as a rule, in methods outside of #Configuration classes and #Bean definitions, developers should only get objects using beans? Specifically, in the case where I want a fresh object, should I inject a prototype bean instead of using the new keyword directly?
One example of code where I'm not sure I'm following Spring conventions is shown below.
// Construct a new object that will be created in the database
RecordDto record = new RecordDto();
// Or should I be using some bean factory?
RecordDto record = RecordDtoFactory.get();
Please read this Article from beloved martin fowler.
I think the IOC concepts is useful when some component in your application has a dependency to other component for some functionality to complete. IoC container will be responsible for managing creation and lifecycle of software components and also inject them in dependent components instead of manually get access to these components instances.
For example, when some Service require an instance of DAO, it will get it from container instead of creating it.
But in case of DTO, they will just hold the data and that is not a real dependency. So I think using "new" is better in this case.

Spring Internal - Member instance injection clarification

Spring creates the class objects by Java dynamic proxies (java.lang.reflect.Proxy). i.e
#Component
public class NewsService implements Service{
}
But how the member variables are injected by Spring? ie
#Autowired
private EntityManager em;
Java dynamic proxies uses interface (i.e Service) to create the objects. But how member variables are injected? The instance variables are not known by interface.
Also when member instances are injected? Load time?(When containing class object is created?) or Lazy loading? (when object is used first?)
Few facts for you:
Spring instantiates specific classes, not interfaces. Dependency injection is done on the original bean instance.
When a proxy is created, Spring registers both the original bean and its proxy in the application context. JDK proxy is created for all interfaces implemented by the original bean.
Proxies are not created if they are not necessary (i.e. no aspect is applied on the target bean).
All beans are eagerly initialized by default. If you want some bean to be instantiated in a lazy fashion, you need to specify it explicitly.
Dependency injection happens right after the bean is instantiated. Some dependencies are injected based on the bean definition, other dependencies might be injected by various bean post processors (but they are executed right away as well).
How is dependency injection realized:
When using XML configuration or autowiring , dependency injection is done via Reflection API. Spring is able to either call property setter (setFoo(...)) or set field value directly (reflection allows setting private members).
When using #Bean methods in Java configuration, dependency injection is done by your method.
A bit on proxies:
JDK proxies and CGLIB proxies are two different proxying mechanisms. JDK creates artificial class based on provided interfaces, whereas CGLIB creates artificial subclass of the target class.
Which proxying mechanism is used depends on your Spring configuration (JDK is the default one). For obvious reasons JDK proxy can be used only in cases when your dependencies are referenced only by interface. From the other side you can not use CGLIB proxying for final classes.

Categories