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

Spring IoC Constructor Injection Example - Tutorial

Constructor Injection: In constructor injection IoC container users construction of dependent class to set the instance of dependency class. We will see example of constructor injection in upcoming tutorials using Spring IoC framework.



SpringExample.java

package com.javastuff.spring;

 public class SpringExample {
 public String message;

 /**
  * @return the message
  */
 public String getMessage() {
  return message;
 }

 /**
  * @param message
  *            the message to set
  */
 public void setMessage(String message) {
  this.message = message;
 }

 public SpringExample(String mess) {
  this.message = mess;
 }
 }


ApplicationContext.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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <bean id="springExample" class="com.javastuff.spring.SpringExample">
  <constructor-arg index="0" type="java.lang.String"
   value="Hello Friend!!!!" />
 </bean>

</beans>
TestClass.java
package com.javastuff.Test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javastuff.spring.SpringExample;

public class TestClass {
 public static void main(String[] args) {
  BeanFactory factory = new ClassPathXmlApplicationContext(
    "ApplicationContext.xml");
  SpringExample se = (SpringExample) factory.getBean("springExample");
  System.out.println(" Message  : " + se.getMessage());
 }
}


Output :
 Message  : Hello Friend!!!!



Related Topics :



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Bean Creation in spring - Tutorial Part - 3

Bean Creation :
  • Direct instantiation
    • <bean id=“beanId” class=“className”>
  • BeanFactory instantiation
    • Same syntax but class is subclass of BeanFactory
    • getObject() called to obtain Bean
  • Static Factory
    • <bean id=“beanId” class=“className" factory-method=" staticCreationMethod“>
  • Instance Factory Method
    • <bean id=“beanId” factory-bean=“existingBeanId" factory-method=“nonStaticCreationMethod">
  • Beans may be singletons or “prototypes”
    • Attribute singleton=“false” causes instantiation with each getBean() lookup
    • Singleton is default
  • XmlBeanFactory pre-instantiates singletons
    • May be overridden on per-instance basis by lazy-init=“true”
  • Beans may also be marked abstract, allowing reuse of attribute values through inheritance
Autowiring Properties :
  • Beans may be auto-wired (rather than using <ref>)
    • Per-bean attribute autowire
    • Explicit settings override
  • autowire=“name”
    • Bean identifier matches property name
  • autowire=“type”
    • Type matches other defined bean
  • autowire=”constructor”
    • Match constructor argument types
  • autowire=”autodetect”
    • Attempt by constructor, otherwise “type”
ApplicationContext :
  • Extends functionality of BeanFactory
  • Pre-instantiates singleton beans
  • Detects and registers BeanPostProcessors and BeanFactoryPostProcessors
  • Supports nesting of contexts
  • ApplicationListener and ApplicationEvents
    • Initialized and closed predefined
    • Custom may be created
  • MessageSource provides i18n messaging
    • <bean id=”messageSource” class=”...ResourceBundleMessageSource”/> Contains list of bundle base names.

Spring IoC (Dependency injection ) Tutorial - Part 2

Inversion of Control :
  • Dependency injection 
    • Beans define their dependencies through constructor arguments or properties.
    • The container provides the injection at runtime.
  • Decouples object creators and locators from application logic 
  • Easy to maintain and reuse.
  • Testing is easier.

Inversion of Control has already been referred to as Dependency Injection. The basic principle is that beans define their dependencies (i.e. the other objects they work with) only through constructor arguments or properties. 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) of the bean instantiating or locating its dependencies on its own using direct construction of classes, or something like the Service Locator pattern. While we will not elaborate too much on the advantages of Dependency Injection, it becomes evident upon usage that code gets much cleaner and reaching a higher grade of decoupling is much easier when beans do not look up their dependencies, but are provided them, and additionally do not even know where the dependencies are located and of what actual type they are.
As touched on in the previous paragraph, Inversion of Control/Dependency Injection exists in two major variants:

setter-based dependency injection is realized by calling setters on your beans after invoking a no-argument constructor to instantiate your bean. Beans defined in the BeanFactory that use setter-based dependency injection are true JavaBeans. Spring generally advocates usage of setter-based dependency injection, since a large number of constructor arguments can get unwieldy, especially when some properties are optional.

constructor-based dependency injection is realized by invoking a constructor with a number of arguments, each representing a collaborator or property. Although Spring generally advocates usage of setter-based dependency injection as much as possible, it does fully support the constructor-based approach as well, since you may wish to use it with pre-existing beans which provide only multi-argument constructors, and no setters. Additionally, for simpler beans, some people prefer the constructor approach as a means of ensuring beans can not be constructed in an invalid state.

Non-IoC / Dependency Injection :



public class OrderServiceImpl implements IOrderService 
{
public Order saveOrder(Order order) throws OrderException
{
 try{  
 // 1. Create a Session/Connection object
 // 2. Start a transaction
 // 3. Lookup and invoke one of the methods in a
  // DAO and pass the Session/Connection object.
 // 4. Commit transaction
 }catch(Exception e){
 // handle e, rollback transaction, //cleanup, // throw e
 }finally{
 //Release resources and handle more exceptions
 }
}

IoC / Dependency Injection :


Program to interfaces for your bean dependencies


public class OrderSpringService implements IOrderService {
IOrderDAO orderDAO;
public Order saveOrder(Order order) throws OrderException{
 // perform some business logic…
 return orderDAO.saveNewOrder(order);
}

public void setOrderDAO(IOrderDAO orderDAO) {
 this.orderDAO = orderDAO;
}
.......
.......
}


The DAO would be injected with a Session/Connection object.

Spring Bean Definition :
  • The bean class is the actual implementation of the bean being described by the BeanFactory.
  • Bean examples – DAO, DataSource, Transaction Manager, Persistence Managers, Service objects, etc
  • Spring config contains implementation classes while your code should program to interfaces.
  • Bean behaviors include:
    • Singleton or prototype
    • Autowiring
    • Initialization and destruction methods 
      • init-method
      • destroy-method
  • Beans can be configured to have property values set. 
    • Can read simple values, collections, maps, references to other beans, etc.
Key attributes :
  • class (required): fully qualified java class name
  • id: the unique identifier for this bean
  • configuration: (singleton, init-method, etc.)
  • constructor-arg: arguments to pass to the constructor at creation time
  • property: arguments to pass to the bean setters at creation time
  • Collaborators: other beans needed in this bean (a.k.a dependencies), specified in property or constructor-arg

    Spring Framework Tutorial - Part1

    What is Spring ?
    • Spring is a Framework, it Provides an infrastructure of classes that make it easier to accomplish tasks.
    • Spring is a Container,it Creates objects and makes them available to your application.
    • A lightweight framework that addresses each tier in a Web application.                     
      1. Presentation layer  :  An MVC framework that is most similar to Struts but is more powerful and easy to use.                                              
      2. Business layer  :  Lightweight IoC container and AOP support (including built in aspects).                                                                      
      3. Persistence layer :  DAO template support for popular ORMs and JDBC
    • Promotes decoupling and reusability.  
    • POJO Based.
    • Removes common code issues like leaking connections and more.
    • Built in aspects such as transaction management.  
     What does Spring provide ?
    • Lightweight container and framework
      • Most of your code will be unaware of the Spring framework
      • Use only the parts you of Spring you want
    • Manages dependencies between your objects
      • Encourages use of interfaces.
      • Lessens “coupling” between objects.
    • Cleaner separation of responsibilities.
      • Put logic that applies to many objects in one single place.
      • Separate the class’s core responsibility from other duties.
    • Simplifies database integration
      • Spring JDBC
      • Hibernate
      • iBATIS
      • Java Persistence API
    Simplify your code with Spring :
    • Enables you to stop polluting code
    • No more custom singleton objects
      • Beans are defined in a centralized configuration file
    • No more custom factory object to build and/or locate other objects
    • DAO simplification
      • Consistent CRUD
      • Data access templates
      • No more copy-paste try/catch/finally blocks
      • No more passing Connection objects between methods
      • No more leaked connections
    • POJO Based
    • Refactoring experience with Spring
    • Caution Spring is addictive.
    IoC(Inversion of Control) container :
    • Setter based and constructor based dependency injection
    • Portable across application servers
    • Promotes good use of OO practices such as programming to interfaces.
    • Beans managed by an IoC container are reusable and decoupled from business logic
    AOP (Aspect-Oriented Programming): 
    • Spring uses Dynamic AOP Proxy objects to provide cross-cutting services
    • Reusable components
    • Aopalliance support today
    • Integrates with the IoC container
    • AspectJ support in Spring 1.1

    Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

    Make sure to activate your subscription by clicking on the activation link sent to your email

    Spring MVC Introduction


    Spring MVC helps in building flexible and loosely coupled web applications. The Model-view-controller design pattern helps in seperating the business logic, presentation logic and navigation logic. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object . Controllers are responsible for receiving the request from the user and calling the back-end services.
    The figure below shows the flow of request in the Spring MVC Framework.
    When a request is sent to the Spring MVC Framework the following sequence of events happen.
    • The DispatcherServlet first receives the request.
    • The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
    • The Controller process the request by calling the appropriate service methods and returns aModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name.
    • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
    • Now the DispatcherServlet will pass the model object to the View to render the result.
    • The View with the help of the model data will render the result back to the user.


    Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

    Make sure to activate your subscription by clicking on the activation link sent to your email