Wednesday, May 27, 2015

Differentiating with dependency injection

Inversion of control( IOC)  is a paradigm giving more control to the targeted components of your application  once getting the work is done .

Dependency injection is a pattern used to create an instances of objects rely on without knowing its compile time which class will be used to provide the functionality . Inversion of control relies on DI(Dependency injection) because mechanism in order to activate the components providing the specific functionality .

Implementation of Inversion of Control design pattern : 

In the object oriented programming these are the basic techniques to implements IOC . These are the following ways .

Using Factory pattern .
Using Service Locator Pattern .
using DI of a given below type : constructor and setter and Interface injections 

IOC in spring framework

The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring’s AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in web applications.

The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring.

There are a number of implementations of the BeanFactory interface. The most commonly used BeanFactory implementation is the XmlBeanFactory class. Other commonly used class is XmlWebApplicationContext. Depending on the bean definition, the factory will return either an independent instance of a contained object (the Prototype design pattern), or a single shared instance (a superior alternative to the Singleton design pattern, in which the instance is a singleton in the scope of the factory). Which type of instance will be returned depends on the bean factory configuration: the API is the same.
Before we dive into dependency injection types, let first identify the ways of creating a bean in spring framework as it will help in understanding the things in next section.

Ways to instantiate beans in spring

A bean definition can be seen as a recipe for creating one or more actual objects. The container looks at the recipe for a named bean when asked, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object.
Instantiation using a constructor
When creating a bean using the constructor approach, all normal classes are usable by and compatible with Spring. That is, the class being created does not need to implement any specific interfaces or be coded in a specific fashion. Just specifying the bean class should be enough. When using XML-based configuration metadata you can specify your bean class like so:

<bean id="exampleBean"/>
Instantiation using a static factory method
When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method itself.

<bean id="exampleBean" factory-method="createInstance"/>
Spring expects to be able to call this method and get back a live object, which from that point on is treated as if it had been created normally via a constructor.
Instantiation using an instance factory method
In a fashion similar to instantiation via a static factory method, instantiation using an instance factory method is where the factory method of an existing bean from the container is invoked to create the new bean.

<bean id="myFactoryBean"  class="...">
 <bean id="exampleBean"  factory-bean="myFactoryBean"  
            factory-method="createInstance"></bean>

Various dependency injection mechanisms

The basic principle behind Dependency Injection (DI) is that objects define their dependencies only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed or returned from a factory method. Then, it is the job of the container to actually inject those dependencies when it creates the bean. This is fundamentally the inverse, hence the name Inversion of Control (IoC).
Setter injection
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.





    public class TestSetter {

    DemoBean demoBean = null;

    public void setDemoBean(DemoBean demoBean) {
        this.demoBean = demoBean;
    }
}
Constructor injection
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. Additionally, calling a static factory method with specific arguments to construct the bean, can be considered almost equivalent, and the rest of this text will consider arguments to a constructor and arguments to a static factory method similarly.
Interface injection In this methodology we implement an interface from the IOC framework. IOC framework will use the interface method to inject the object in the main class. It is much more appropriate to use this approach when you need to have some logic that is not applicable to place in a property. Such as logging support.
public void SetLogger(ILogger logger)
{
  _notificationService.SetLogger(logger);
  _productService.SetLogger(logger);
}

Some commonly asked interview questions

What is difference between component and service?
A component is a glob of software that’s intended to be used, without change, by an application that is out of the control of the writers of the component. By ‘without change’ means that the using application doesn’t change the source code of the components, although they may alter the component’s behavior by extending it in ways allowed by the component writers.
A service is similar to a component in that it’s used by foreign applications. The main difference is that a component to be used locally (think jar file, assembly, dll, or a source import). A service will be used remotely through some remote interface, either synchronous or asynchronous (eg web service, messaging system, RPC, or socket.)
How DI is different from Service locator pattern?
The key benefit of a Dependency Injector is that it allows to plug-in a suitable implementation of a service according to environment and usage. Injection isn’t the only way to break this dependency, another is to use a service locator. The basic idea behind a service locator is to have an object that knows how to get hold of all of the services that an application might need. It then scans all such services and store them as a singleton Registry. When asked for a service implementation, a requester can query the registry with a token and get appropriate implementation.
Mostly these registries are populated via some configuration files. The key difference is that with a Service Locator every user of a service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the locator.
Which one should be better to use i.e. service locator or dependency injection?
Well, it as I already said that key difference is that with a Service Locator every user of a service has a dependency to the locator. It means you must know the details of service locator in terms of input and output. So, it actually becomes the deciding factor which pattern to choose from.
If it is easy and necessary to maintain registry information then go for service locator, or else simply use dependency injection as it does not bother the users of service with any per-requisites.
Which is better constructor injection or setter injection?
The choice between setter and constructor injection is interesting as it mirrors a more general issue with object-oriented programming -- should you fill fields in a constructor or with setters.
Constructors with parameters give you a clear statement of what it means to create a valid object in an obvious place. If there’s more than one way to do it, create multiple constructors that show the different combinations. Another advantage with constructor initialization is that it allows you to clearly hide any fields that are immutable by simply not providing a setter. I think this is important -- if something shouldn’t change then the lack of a setter communicates this very well. If you use setters for initialization, then this can become a pain.
But If you have a lot of constructor parameters things can look messy, particularly in languages without keyword parameters. If you have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on the number and type of parameters. Constructors also suffer if you have simple parameters such as strings. With setter injection you can give each setter a name to indicate what the string is supposed to do. With constructors you are just relying on the position, which is harder to follow.
My preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I’ve outlined above start to become a problem.
What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
·         A means for resolving text messages, including support for internationalization.
·         A generic way to load file resources.
·         Events to beans that are registered as listeners.
What are the common implementations of the Application Context ?
The three commonly used implementation of ‘Application Context’ are
1) ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application’s classpath by using the code .
ApplicationContext context = new ClassPathXmlApplicationContext(“bean.xml”);
2) FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
ApplicationContext context = new FileSystemXmlApplicationContext(“bean.xml”);
3) XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
What should be used preferably BeanFactory or ApplicationContext?
A BeanFactory pretty much just instantiates and configures beans. An ApplicationContext also does that, and it provides the supporting infrastructure to enable lots of enterprise-specific features such as transactions and AOP. In short, favor the use of an ApplicationContext.



3 comments:

  1. Thanks for sharing this informative content , Great work
    Creative Thinking for creating an impact!
    Product Thinking Community introduces PT Labs powered by Leanpitch
    Devops Online Training

    ReplyDelete
  2. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product prototyping during this lockdown period everyone can use it wisely.
    icp-cat training

    ReplyDelete
  3. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in ICP CAT during this lockdown period everyone can use it wisely.
    ICP-CAT certification

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...