Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Monday, 22 May 2017

What are the different types of dependency injections in spring?

Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies into the object externally, and you make it somebody else's problem. This "someone" is either an object further up the dependency graph, or a dependency injector (framework) that builds the dependency graph.

Spring supports 2 types of dependency injection
Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument.

1) Constructor- based dependency injection
It is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

2) Setter-based dependency injection
It is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Spring Setter vs. Constructor Injection
1. Partial dependency: Partial dependency can be injected using setter injection but it is not possible by the constructor. Suppose there are 4 properties in a class, having 4 arguments constructor and setters methods. In such case, if you want to pass information to only one property, it is possible by setter method only.

2. Overriding: Setter injection overrides the constructor injection. If we use constructor and setter injection, IOC container will use the setter injection.

3. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like a constructor. So setter injection is flexible than constructor injection.

4. Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml.

5. There is one drawback of setter Injection is Security. By using setter injection, we can override certain dependency which is not possible which is not possible with constructor injection because every time we call the constructor, a new object is gets created.

6. Setter and Constructor injection in Spring, where later can help if there is a circular dependency between two object A and B.

When to use Setter Injection over Constructor Injection in Spring?
Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring, we use XML files, readability is a much bigger concern. Also, the drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using "dependency-check" attribute of the tag.

Once the number of dependencies crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via the constructor. Setter Injection is preferred choice when the number of dependencies to be injected is a lot more than normal, if some of those arguments are optional than using Builder design pattern is also a good option.

Tuesday, 12 July 2016

Inversion of control (IoC) and dependency injection

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

Example: Our application has a text editor component and we want to provide spell checking.

Our standard code would look something like this:
public class TextEditor {
       private SpellChecker checker;
       public TextEditor() {
              this.checker = new SpellChecker();
       }
}

What we've done here is create a dependency between the TextEditor and the SpellChecker.

In an IoC scenario we would instead do something like this:
public class TextEditor {
       private ISpellChecker checker;
       public TextEditor(ISpellChecker checker) {
              this.checker = checker;
       }
}

Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the TextEditor with the dependency.

It 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.

IoC containers:
1. BeanFactory
2. ApplicationContext

Dependency injection may happen through 3 ways:
1. Constructor injection.
2. Setter injection.
3. Interface injection

Sunday, 10 July 2016

Spring Bean

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.

Any normal Java POJO class can be a Spring Bean that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML definitions.

Spring/IoC container

The Spring/IoC container is at the core of the Spring Framework. It is responsible to instantiate, wire them together, configure them, and manage their complete lifecycle from creation till destruction.

The spring container uses dependency injection (DI) to manage the components that make up an application. The IoC container gets informations from the XML file and works accordingly.

Major tasks performed by IoC container:
To instantiate the application class
To configure the object
To assemble the dependencies between the objects

Different type of IoC containers:
1. BeanFactory
interface org.springframework.beans.factory.BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface.
Resource resource = new ClassPathResource("applicationContext.xml");  
BeanFactory factory = new XmlBeanFactory(resource); 
Employee s = (Employee) factory.getBean("e");
The constructor of XmlBeanFactory class receives the Resource object so we need to pass the resource object to create the object of BeanFactory.

2. ApplicationContext
interface org.springframework.context.ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface.
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");


Sunday, 22 May 2016

The prefix "mvc" for element "mvc:annotation-driven" is not bound.


<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
Error: The prefix "mvc" for element "mvc:annotation-driven" is not bound.

Due to missing of annotation: 
xmlns:mvc="http://www.springframework.org/schema/mvc"


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:beans="http://www.springframework.org/schema/beans"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

Wednesday, 20 April 2016

Injecting a prototype bean into a singleton bean

Problem: If we will inject the prototype bean into singleton bean; by default it will be singleton i.e. it will not behaving like prototype bean.

autowiring-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd"

       default-autowire="byName" default-autowire-candidates="*">

       <context:annotation-config />

       <bean id="employee" class="spring.core.proto.in.sing.Employee" scope="singleton">
              <property name="id" value="1"></property>
              <property name="name" value="Rajesh kumar"></property>
              <property name="profile" value="developer"></property>
       </bean>

       <bean id="two" class="spring.core.proto.in.sing.PastInformation" scope="prototype">
              <property name="lastCompany" value="ABC2"></property>
       </bean>
</beans>

package spring.core.proto.in.sing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Employee {
       private int id;
       private String name;
       private String profile;

       @Autowired
       @Qualifier("two")
       private PastInformation lastSecond;

       // setters and getters

       public void displayInfo() {
              lastSecond.displayInfo("last");
              String empDetails="id : "+id+" name : "name + " profile : " + profile;
              System.out.println(empDetails);
       }
}

package spring.core.proto.in.sing;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestIOC {
       private static ApplicationContext appContext;
       public static void main(String[] args) {
              appContext = new ClassPathXmlApplicationContext
                              ("spring/core/proto/in/sing/autowiring-spring.xml");
              Employee empl1 = appContext.getBean("employee", Employee.class);

              empl1.displayInfo();
             
              Employee empl2 = appContext.getBean("employee", Employee.class);

              if(empl1==empl2) {
                     System.out.println("singleton !!");
              }

              /* This line should not print for prototype scope coz both     
              instance will be different. */
              if(empl1.getLastSecond()==empl2.getLastSecond()) {
                     System.out.println("singleton : not prototype as per scope !!");
              }
       }
}

Output:
last : ABC2
id : 1 name : Rajesh kumar profile : developer
singleton !!
singleton : not prototype as per scope !!

Resolve using Interface ObjectFactory:


package spring.core.proto.in.sing;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Employee {
       @Autowired
       @Qualifier("two")
       private ObjectFactory<PastInformation> myPrototypeFactory;

       private int id;
       private String name;
       private String profile;

       public void displayInfo() {
              myPrototypeFactory.getObject().displayInfo("last");
              String empDetails="id : "+id+" name : "name + " profile : " + profile;
              System.out.println(empDetails);
       }

       public PastInformation getLastSecond() {
              return myPrototypeFactory.getObject();
       }
      
       public ObjectFactory<PastInformation> getMyPrototypeFactory() {
              return myPrototypeFactory;
       }

       public void setMyPrototypeFactory(
                     ObjectFactory<PastInformation> myPrototypeFactory) {
              this.myPrototypeFactory = myPrototypeFactory;
       }
}

Now, output:
last : ABC2
id : 1 name : Rajesh kumar profile : developer
singleton !!

Lookup Method injection
The Spring Framework implements method injection by using CGLIB library to generate dynamically a subclass that overrides the method. So for the method to be overridden, we have to define that method in the class and either provide a dummy implementation for it or make it abstract.

Making a method abstract implies that class also has to be made abstract which will make it difficult to unit test. So providing a dummy implementation is a better choice.

Whenever we define a bean with lookup methods, spring creates a subclass of the bean and overrides those methods which are marked as lookup-methods and this sub classed bean gets registered into the context. The subclass delegates all the non-lookup methods to the original class.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd"
       default-autowire="byName" default-autowire-candidates="*">

       <context:annotation-config />

       <bean id="employee" class="spring.core.proto.in.sing.Employee"
              scope="singleton">
              <property name="id" value="1"></property>
              <property name="name" value="Rajesh kumar"></property>
              <property name="profile" value="developer"></property>
              <lookup-method name="getLastSecond" bean="two"/>
       </bean>


       <bean id="two" class="spring.core.proto.in.sing.PastInformation"
              scope="prototype">
              <property name="lastCompany" value="ABC2"></property>

       </bean>
</beans>

Now, output:
last : ABC2
id : 1 name : Rajesh kumar profile : developer
singleton !!

Scoped Proxies:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd"

       default-autowire="byName" default-autowire-candidates="*">

       <context:annotation-config />

       <bean id="employee" class="spring.core.proto.in.sing.Employee"
              scope="singleton">
              <property name="id" value="1"></property>
              <property name="name" value="Rajesh kumar"></property>
              <property name="profile" value="developer"></property>
              <lookup-method name="getLastSecond" bean="two" />
       </bean>


       <bean id="two" class="spring.core.proto.in.sing.PastInformation"
              scope="prototype">
              <property name="lastCompany" value="ABC2"></property>
            <aop:scoped-proxy />
       </bean>
</beans>

Related Posts Plugin for WordPress, Blogger...