Tuesday, 28 April 2015

Java Source World: Spring Framework- Constructor Injection with Dependent Object

Constructor Injection with Dependent Object





Spring Framework- Constructor Injection with Dependent Object



If there is HAS-A relationship between the classes, we create the instance of dependent object (contained object) first then pass it as an argument of the main class constructor. Here, our scenario is Employee HAS-A Address. The Address class object will be termed as the dependent object. Let's see the Address class first:

Address.java

This class contains three properties, one constructor and toString() method to return the values of these object.

    package com.springexample; 
    

    public class Address { 
    private String city; 
    private String state; 
    private String country; 
     
    public Address(String city, String state, String country) { 
        super(); 
        this.city = city; 
        this.state = state; 
        this.country = country; 
    } 
     
    public String toString(){ 
        return city+" "+state+" "+country; 
    } 
    } 

Employee.java

It contains three properties id, name and address(dependent object) ,two constructors and show() method to show the records of the current object including the depedent object.

    package com.springexample; 
     
    public class Employee { 
    private int id; 
    private String name; 
    private Address address;//Aggregation 
     
    public Employee() {System.out.println("def cons");} 
     
    public Employee(int id, String name, Address address) { 
        super(); 
        this.id = id; 
        this.name = name; 
        this.address = address; 
        
    void show(){ 
        System.out.println(id+" "+name); 
        System.out.println(address.toString()); 
    }      
    } 

applicationContext.xml

The ref attribute is used to define the reference of another object, such way we are passing the dependent object as an constructor argument.

    <?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:p="http://www.springframework.org/schema/p" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="a1" class="com.springexample.Address"> 
    <constructor-arg value="ghaziabad"></constructor-arg> 
    <constructor-arg value="UP"></constructor-arg> 
    <constructor-arg value="India"></constructor-arg> 
    </bean>        
    <bean id="e" class="com.springexample.Employee"> 
    <constructor-arg value="12" type="int"></constructor-arg> 
    <constructor-arg value="Sonoo"></constructor-arg> 
    <constructor-arg> 
    <ref bean="a1"/> 
    </constructor-arg> 
    </bean> 
    </beans> 

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.

    package com.springexample; 
           
    import org.springframework.beans.factory.BeanFactory; 
    import org.springframework.beans.factory.xml.XmlBeanFactory; 
    import org.springframework.core.io.*; 
     
    public class Test { 
        public static void main(String[] args) { 
             
            Resource r=new ClassPathResource("applicationContext.xml"); 
            BeanFactory factory=new XmlBeanFactory(r); 
             
            Employee s=(Employee)factory.getBean("e"); 
            s.show(); 
             
        } 


Read More »

Sunday, 26 April 2015

Java Source World: REST Web services

 

REST Web services


REST - Representational State Transfer

What is REST:

REST is an architectural style which is based on web-standards and the HTTP protocol. REST was first described by Roy Fielding in 2000.
In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods.
In a REST based architecture you typically have a REST server which provides access to the resources and a REST client which accesses and modifies the REST resources.
Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).
REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation).

 HTTP methods

The PUT, GET, POST and DELETE methods are typical used in REST based architectures.
The following table gives an explanation of these operations.
·    GET defines a reading access of the resource without side-effects. The resource is never changed via a GET request, e.g., the request has no side effects (idempotent).
·    PUT creates a new resource. It must also be idempotent.
·    DELETE removes the resources. The operations are idempotent. They can get repeated without leading to different results.
·    POST updates an existing resource or creates a new resource.

 RESTFul web services

A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul web service typically defines the base URI for the services, the supported MIME-types (XML, text, JSON, user-defined, ...) and the set of operations (POST, GET, PUT, DELETE) which are supported.
JAX-RS with Jersey

JAX-RS:

Java defines REST support via the Java Specification Request (JSR) 311. This specification is called JAX-RS (The Java API for RESTful Web Services). JAX-RS uses annotations to define the REST relevance of Java classes.

 Jersey

Jersey is the reference implementation for the JSR 311 specification.
The Jersey implementation provides a library to implement Restful webservices in a Java servlet container.
On the server side Jersey provides a servlet implementation which scans predefined classes to identify RESTful resources. In your web.xml configuration file your register this servlet for your web application.
The Jersey implementation also provides a client library to communicate with a RESTful webservice.
The base URL of this servlet is:
http://your_domain:port/display-name/url-pattern/path_from_rest_class 
This servlet analyzes the incoming HTTP request and selects the correct class and method to respond to this request. This selection is based on annotations in the class and methods.
A REST web application consists, therefore, out of data classes (resources) and services. These two types are typically maintained in different packages as the Jersey servlet will be instructed via the web.xml to scan certain packages for data classes.
JAX-RS supports the creation of XML and JSON via the Java Architecture for XML Binding (JAXB).



Read More »

Friday, 24 April 2015

Java Source World: About Spring Framework

About Spring Framework


What is Spring
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

Spring Basic:
Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc. The framework, in broader sense, can be defined as a structure where we find solution of the various technical problems.
The spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc. We will learn these modules in next page. Let's understand the IOC and Dependency Injection first.

Inversion Of Control (IOC) and Dependency Injection:
These are the design patterns that are used to remove dependency from the programming code. They make the code easier to test and maintain. Let's understand this with the following code:

    class Employee{ 
    Address address; 
    Employee(){ 
    address=new Address(); 
    } 
    } 

In such case, there is dependency between the Employee and Address (tight coupling). In the Inversion of Control scenario, we do this something like this:

    class Employee{ 
    Address address; 
    Employee(Address address){ 
    this.address=address; 
    } 
    } 

Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if our logic is moved to new environment.

In Spring framework, IOC container is responsible to inject the dependency. We provide metadata to the IOC container either by XML file or annotation.

Advantage of Dependency Injection

·         makes the code loosely coupled so easy to maintain
·         makes the code easy to test

Advantages of Spring Framework

There are many advantages of Spring Framework. They are as follows:

1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need to write too much code. It hides the basic steps of these technologies.

Let's take the example of JdbcTemplate, you don't need to write the code for exception handling, creating connection, creating statement, committing transaction, closing connection etc. You need to write the code of executing query only. Thus, it save a lot of JDBC code.

2) Loose Coupling
The Spring applications are loosely coupled because of dependency injection.

3) Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application require server to run the application but Spring framework doesn't require server.

4) Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.

5) Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy development of JavaEE application.

6) Powerful abstraction
It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.

7) Declarative support
It provides declarative support for caching, validation, transactions and formatting.

Read: Spring Modules




Read More »