Spring IOC and Dependancy Injection

In Spring, Inversion of Control(IOC) is implemented using Dependancy Injection(DI) Design Pattern. Let's understand DI with java example and then I will see how DI can solve tightly coupled problem and Spring container will inject dependency.

What is Inversion of Control?
IOC allows you to decouple your program into separate components that don't know each other. supposed if I have two classes which implements common interface then In order to use, In my Java class i need to create instance of those classes. which looks like tightly coupled.

If we can define which class to use at runtime using Injecting dependency at runtime then it will be good , right? This is where IOC comes to Picture.

Concept IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection.

There are three forms or styles of Dependency Injection.
1.Constructor Injection
2.Setter Injection
3.Interface Injection

1. Constructor Injection: Here, IoC container uses the constructor to inject the dependency. Since All dependencies are declared in one constructor, it's added advantage.
- here, handling over dependencies takes during instantiation of the dependent object.

2. Setter Injection: Here, DI uses Setters to inject the required resources or dependencies.Meaning class will have setters, the IoC container will use the setters to provide the resource at run-time.
-  here, handling over dependencies takes after the dependent object is instantiated

What is Spring and why came into Picture ?

In order to start with Spring, it's very important to clear concepts about what is Spring and why it came into picture. Once you have idea about Spring picture, you will be sure able to easily understand 7 Spring modules described here as well. So Let's Jump into Spring :)

Java Enterprise Edition (JEE) component that was used to implement business logic was Enterprise Java Beans (EJB). However, EJBs are heavy weight components that require application servers to run. 

This was the scenario before the Spring Framework came into the picture. The Spring Framework provides a lightweight container to run the objects implementing business logic. In other words, Spring Framework-based business objects do not require an application server to run.

Spring Framework: What is it? Spring Framework is “An open-source layered Java/J2EE application framework having a light-weight container implementing Inversion-of-Control and Aspect Oriented Programming.” The key points here are “layered application framework” and “Inversion of Control and Aspect Oriented Programming.” and they are divided into two broad categories:
  1. Patterns
  2. Components of the Framework

Spring has two patterns at its core. They are:
    • Inversion-of-Control(IOC)
    • Aspect Oriented Programming(AOP)

Inversion-of-Control - refer to Spring DI and IOC concept and Example

Aspect Oriented Programming(AOP) is “An approach to programming that attempts the separation of concerns, specifically cross-cutting concerns, as an advance in modularization.” Here, the key point is separation of concerns. 

Separation of concerns means that the applications are divided into modules that do not overlap in terms of functionality.Logging is an example of such a concern.by using AOP a developer can encapsulate cross cutting concerns.

Using Spring JdbcTemplate to store and retrive values into DB

In This example i will demonstrate you Spring example to insert and select values from oracle DB. The insertForum() method below shows the amount of code you need to write to insert data using JDBC.

1. Create Java POJO Class ex. Forum which contains getter and setter method for field as mentioned below.
    private int forumId;
    private String forumName;
    private String forumDesc;


1.1 create parameterized constructor as below.
  public Forum(int forumId, String forumName, String forumDesc) {
        this.forumId = forumId;
        this.forumName = forumName;
        this.forumDesc = forumDesc;
    }
 

2. Create Interface ex. ForumDAO which contains insert and select methods
package com.learning.dao;
import com.learning.core.Forum;
public interface ForumDAO {

    public void insertForum(Forum forum);
    public Forum selectForum(int forumId);
}


Hibernate - Store and Retrieve Data along with BLOB as XML

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.

Here, i have demostrated basic example to store data along with blob into Database and retrieve from Database.File logic is used to display Blob Data only. While writing your own Logic, you should avoid it.

Before Using this tutorial, You need know how hibernate Configuration "hibernate.cfg.xml" should look like. Read related blog post - Hibernate config file

How to write Code in Java?

If you Google then you will find lots of code and solution of your coding issue. but
The most important point is How Code should be?
When you are writing code in Java, As per my knowledge - There are points which should be implemented into code

Key Pointes are :

1. Always generate logs for your application.You can use apache Log4j.jar for that.

2. Don't generate log file into root of your application. Try to create new Log directory into your application,
   and generate new log file for earch Run/Build into log folder

3. Naming convension of log file is important as well. it should be Ex. _DataandTimeStamp.log.
   In order to create new log file each time your applicaton runs, you can create inherit superclass FileAppender
   and overrid it's method and write logic to create new name with timestamp.


4. If your application require Global variable,which will be used throught your appplication(like Configuration) then you
   should make define it into Properties and access it using ResourceBundle from Java.util package.
 

5. Exception Handling is one of the important factor which should be implemented into your program.

6. Don't use static absolute path. Better to use relative path Ex. path config/Resource.properties is better than
   c:/myproject/src/config/Resource.properties


7. Write all your java files into packages rather than in Default package

Marshelling and Unmarshelling Document using JAXB

Marshelling is a process of transforming java objects into XML format. and Unmarshalling is the process of converting an XML document into a corresponding set of Java objects.

Concept 1 : Marshelling Document
Create JAXBContext object as per your project as
JAXBContext jaxbContext;
jaxbContext = JAXBContext.newInstance("com.anuj.jaxb");

Once your domain object is initialized, use the JAXB context to create a Marshaller object and a typed JAXBElement. Creating the marshaller is simple:
Marshaller marshaller = jaxbContext.createMarshaller();

You can Set a property so that the output will be formatted for human use and then write to standard output
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal( bookingElement, System.out );  Outout will be XML.

Generate .xsd Schema file from .xml file

When you are using JAXB(Java Architecture for XML Binding), you must require xml document to be converted into .xsd file. There is one Open Source called "trang" which does same thing. It takes .xml file as input and give .xsd as output. You can also use XMLSpy but It's not free. you will be provided 30 days trial.

1. Download "Trang"and Copy .jar files to local
2. Generate .xsd file using command as below using command prompt

java -jar trang.jar app-defaults.xml app-defaults.xsd

Note : app-defaults.xml is existing input .xml file and app-defaults.xsd is file which will generate after running this command.