Autowiring vs new Object Keyword

Autowiring new Object()
decouples object creation and life-cycle from object binding and usage Using new Keyword creates new Object everytime.The object graph grows over a period of time.Consider UserDaoImpl perhaps needs a Hibernate session, which needs a DataSource, which needs a JDBC connection – it quickly becomes a lot of objects that has to be created and initialized over and over again. When you rely on new in your code
Autowiring offers object at different scopes – Singleton, request and prototype All objects are JVM Scope

How Autowiring works
The autowiring happens when the application starts up, during the time of deployment.When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically.

Lets see a example where the dependencies are resolved by XML and annotation
ApplicationContext.xml

<beans ...>
    <bean id="userService" class="com.foo.UserServiceImpl"/>
    <bean id="fooController" class="com.foo.FooController"/>
</beans>

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than 1 UserService bean, then you’ll have to qualify which one it should use.

FooController.java

public class FooController 
{
    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

Things to Note while Autowiring

  1. Marks a constructor, field, setter method or config method as to be autowired by Spring’s dependency injection facilities.
  2. Only one constructor (at max) of any given bean class may carry this annotation, indicating the constructor to autowire when used as a Spring bean. Such a constructor does not have to be public.
  3. Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.
  4. •In the case of multiple argument methods, the ‘required’ parameter is applicable for all arguments.

Annotation or XML
For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code’s dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.

However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.

I haven’t used JPA annotations, so I don’t know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn’t care where its information came from.If an annotation provides functionality and acts as a comment in and of itself, and doesn’t tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won’t change the main functionality of the code, and hence doesn’t belong in the source files.

How auto wiring works in Spring

  1. All Spring beans are managed – they “live” inside a container, called “application context”.the application context is bootstrapped and all beans – autowired. In web applications this can be a startup listener.
  2. All application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver
  3. the context instantiates the objects, not you. I.e. – you never make new UserServiceImpl() – the container finds each injection point and sets an instance there.
  4. applicationContext.xml you should enable the so that classes are scanned for the @Controller, @Service, etc. annotations.
  5. Apart from the @Autowired annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring – to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resource can also be used
  1. AnnotationSessionFactoryBean is used to create session factory if hibernate pojo are annotated
  2. AnnotationSessionFactoryBean is a factory that produces SessionFactory automatically.This is used when you create a sessionFactory object of Hibernate from Spring
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.
    annotation.AnnotationSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="annotatedClasses">
         <list>
           <value>test.package.Foo</value>
           <value>test.package.Bar</value>
         </list>
       </property>
     </bean>
    
  3. This session factory is assigned to all dao beans and hibernate template to do database transaction.
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.
    HibernateTemplate">
    	<property name="sessionFactory">
    	  <ref bean="sessionFactory" />
    	</property>
    </bean>
    <bean id="pageDao" class="com.concretepage.dao.PageDaoImpl">
        <property name="hibernateTemplate">
    	  <ref bean="hibernateTemplate" />
    	</property>
    </bean>
    

Spring vs EJB

App servers written to support the EJB standard can, in theory, be ported from one compliant Java EE app server to another. But that means staying away from any and all vendor-specific extensions that lock you in to one vendor.

Spring ports easily between app servers (e.g., WebLogic, Tomcat, JBOSS, etc.) because it doesn’t depend on them

Spring Boot offers an even better way to write applications without Java EE app servers. You can create an executable JAR and run it on a JVM.

The Spring framework sits on top of the application servers and service libraries. Service integration code (e.g. data access templates) resides in the framework and is exposed to the application developers. In contrast, the EJB 3 framework is integrated into the application server and the service integration code is encapsulated behind an interface. EJB 3 vendors can thus optimize the performance and developer experience by working at the application server level. For example, they can tie the JPA engine closely to JTA transaction management. Another example is clustering support which is transparent to EJB 3 developers

Spring vs J2EE

Strictly speaking, Spring is a framework while Java EE is a specification which is implemented by various softwares such as JBoss and Glassfish.
The greatest difference is that Spring is an actual library while JavaEE is an API that has to be implemented. Depending on the JAVA EE container you could find a full implementation (e.g. Glassfish), a partial implementation (e.g. Tomcat) a full implementation with extra sugar (e.g. JBoss and others).

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.Inversion of Control (IoC) means any sort of programming style where an overall framework or run-time controlled the program flow.

Dependency Injection is a Type of IoC

IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside service (for example, xml file or single app service).

DI means the IoC principle of getting dependent object is done without using concrete objects but abstractions (interfaces). This makes all components chain testable, cause higher level component doesn’t depend on lower level component, only from interface.

Techniques to implement inversion of control

  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    1. a constructor injection
    2. a setter injection
    3. an interface injection

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI Frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in implementations.

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

Say the Excel Jar files with utility methods used the application uses the methods in the Utility Class and the flow is controlled by the way the method gets called in order the get the things done.

whereas

In framework like spring the implementation is defined in XML files and by using annotation and the framework calls the methods as per defined in xml.

Without Ioc

  Application -> Methods -> Framework      

With Ioc

  Framework -> XML File ->  Method Call (or) Implementation      

Inversion of Control(IoC) Container:
Common characteristic of frameworks IOC manages java objects

  1. From instantiation to destruction through its BeanFactory.
  2. 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.

Flow of control is “inverted” by dependency injection because you have effectively delegated dependencies to some external system

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

For example, say your application has a text editor component and you want to provide spell checking. Your 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.

Without IoC: you ask for “apple”, and you are always served apple when you ask more.

With IoC:
You can ask for “fruit”. You can get different fruits each time you get served. for example, apple, orange, or water melon.

Inversion of Control, (or IoC), is about getting
freedom (You get married, you lost freedom and you are being controlled. You divorced, you have just implemented Inversion of Control. That’s what we called, “decoupled”. Good computer system discourages some very close relationship.)

flexibility (The kitchen in your office only serves clean tap water, that is your only choice when you want to drink. Your boss implemented Inversion of Control by setting up a new coffee machine. Now you get the flexibility of choosing either tap water or coffee.)

less dependency (Your partner has a job, you don’t have a job, you financially depend on your partner, so you are controlled. You find a job, you have implemented Inversion of Control. Good computer system encourages in-dependency.)

Dependency Injection

What is Dependency

Quick Example:EMPLOYEE OBJECT WHEN CREATED,
              IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT
   (if address is defines as dependency by Employee object)

Now in the above EMPLOYEE Class is dependent on ADDRESS Class.

You can not create the Address Object unless you create Employee Object

EMPLOYEE Class is dependent and ADDRESS Class is dependency

What is the purpose of DI?
With dependency injection, objects don’t define their dependencies themselves, the dependencies are injected to them as needed.The purpose of Dependency Injection is to reduce coupling in your application to make it more flexible and easier to test.

How does it benefit ? The objects don’t need to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.

When to use Dependency Injection
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up ‘test’ data.Dependency Injection gives you the ability to test specific units of code in isolation.

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It’s a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g Spring) to do that, but they certainly aren’t required.

Example
A Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object

Without Dependency Injection (DI):

class Car
{
  private Wheel wh   = new ApolloWheel();
  private Battery bt = new ExideBattery();

  //The rest
}

Here, the Car object is responsible for creating the dependent objects.

What if we want to change the type of its dependent object – say Wheel – after the initial ApolloWheel() punctures? We need to recreate the Car object with its new dependency say SpareWheel(), but only the Car manufacturer can do that.

Then what does the Dependency Injection do us for…?

When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.

After using dependency injection:

class Car
{
  private Wheel wh   = [Inject an Instance of Wheel at runtime];
  private Battery bt = [Inject an Instance of Battery at runtime];

  Car(Wheel wh,Battery bt) 
  {
      this.wh = wh;
      this.bt = bt;
  }

  //Or we can have setters
  void setWheel(Wheel wh) 
  {
      this.wh = wh;
  }
}

Lets take the below example

public class Foo
{
    private Bar _bar;

    public Foo(Bar bar)
    {
        _bar = bar;
    }

    public bool IsPropertyOfBarValid()
    {
        return _bar.SomeProperty == PropertyEnum.ValidProperty;
    }
}

without dependency injection the Bar object is dependent and tightly coupled with Foo class like below

public class Foo
{
    private Bar _bar = new Bar();
    .
    . 
}

But by using dependency injection like before code you can mock the Bar Object at runtime and call the IsPropertyOfBarValid() method over it.

add_person.jsp

<body>
  <form name="frmTest" id="frmTest" method="post" action="/Test2/Control1/displayPerson">
    <input type="text" name="Name" />I Agree
	<select name="Location">
  	  <option value="Teynampet">Teynampet</option>
	  <option value="TNagar">TNagar</option>
	  <option value="Adyar">Adyar</option>
	</select>
    <input type="checkbox" name="cboAgree" value="I Agree"/>I Agree		
    <input type="submit" name="btnSubmit" value="Submit"/>		
  </form>
</body>

Person.java

public class Person 
{
	private String Name;
	private String Location;	
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public String getLocation() {
		return Location;
	}
	public void setLocation(String location) {
		Location = location;
	}

        @Override
	public String toString() 
        {
	  return "Person [Name=" + Name + ", Location=" + Location + "]";
	}
}

TestController .java

@Controller
@RequestMapping("/Control1")
public class TestController 
{
	@RequestMapping(value="/displayPerson", method=RequestMethod.POST)
	public String TestMe4(@ModelAttribute Person person)
	{
		System.out.println(person); 
		return "add_person";
	}
}

Output

Person [Name=Mac, Location=TNagar]

DAOService.java

public class DAOService 
{
	private List<Person> arrPersons = new ArrayList<Person>(); 
			
	public DAOService()
	{
		
		Person objPerson = new Person();
		objPerson.setName("Person 1");
		objPerson.setLocation("Teynampet");
		
		arrPersons.add(objPerson);
		
		Person objPerson2 = new Person();
		objPerson2.setName("Person 2");
		objPerson2.setLocation("TNagar");
		
		arrPersons.add(objPerson2);
	}

	public List getList()
	{
		return this.arrPersons;
	}
}

ListPerson.java

@Controller
@RequestMapping("/List")
public class ListPerson 
{	
	@Autowired
	private DAOService objDAOService;
	
	@RequestMapping("/PersonList")
	public String listPersons(Model model)
	{
		DAOService objDAOService = new DAOService();
		
		model.addAttribute("personList", this.objDAOService.getList());
		
		return "display_list";
	}
}

display_list.jsp

<title>Insert title here</title>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</head>
<body>	
	<table>
		<c:forEach items="${personList}" var="objPerson"> 
			<tr>
				<td>${objPerson.name}</td>
				<td>${objPerson.location}</td>
			</tr>
		</c:forEach>
	</table>
</body>

applicationContext.xml

<bean name="DAOService" class="com.mugil.controls.DAOService"></bean>

pom.xml

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

Method Arguments in Controller

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
	@RequestMapping("/Control2")		
	public String TestMe(HttpSession session, HttpServletRequest request)
	{
		request.setAttribute("name", "Mugil Vannan");
		session.setAttribute("Test", "TestValue");
		System.out.println("1");
		return "hello";
	}
	
	@RequestMapping(value="/Control2", method=RequestMethod.POST)
	public String TestMe2(HttpSession session, HttpServletRequest request)
	{
		System.out.println(session.getAttribute("Test"));
		System.out.println(request.getParameter("cboArea"));		
		return "display";
	}
}

Alternate of HttpServletRequest request

@RequestMapping(value="/Control2", method=RequestMethod.POST)
public String TestMe2(HttpSession session, @RequestParam("cboArea") String Area)
{
  System.out.println(session.getAttribute("Test"));
  System.out.println(Area);		
  return "display";
}

hello.java

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="frmTest" id="frmTest" method="post">		
	<select name="cboArea">
		<option value="Teynampet">Teynampet</option>
		<option value="TNagar">TNagar</option>
		<option value="Adyar">Adyar</option>
	</select>		
	<input type="checkbox" name="cboAgree" value="I Agree"/>I Agree		
	<input type="submit" name="btnSubmit" value="Submit"/>		
</form>
</body>
</html>

TestController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
	@RequestMapping("/Control2")		
	public String TestMe()
	{
		return "hello";
	}

	@RequestMapping(value="/Control2", method=RequestMethod.POST)
	public String TestMe2()
	{
		System.out.println("Hi there");
		return "hello";
	}

	@RequestMapping(value="/Control2", method=RequestMethod.POST, params={"cboArea=TNagar", "cboAgree"})
	public String TestMe3()
	{
		System.out.println("I am in TNagar");
		return "hello";
	}
}

Simple Controller Example
TestController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
  @RequestMapping("/Control2")	
  public String TestMe()
  {
    return "hello";
  }
}

hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   Hi Dear!
</body>
</html>