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

Spring Bean Init and Destroy method Configuration Example

In Spring, you can use init-method and destroy-method as attribute in bean configuration file for bean to perform certain actions upon initialization and destruction 

Beans can be initilized by the factory before its first use

public class ExampleBean {
      public void init () {
           // do some initialization work
       }
  }

<bean id="exampleBean" class="ExampleBean" init-method="init"/>


Beans can be cleaned up when not used any more

public class ExampleBean {
      public void cleanup () {
           // do some destruction work
       }
  }

<bean id="exampleBean" class="ExampleBean" destroy-method="cleanup"/>



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

What and Why Inversion of Control ? Explain IoC types ?

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.



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

Purpose of the ApplicationContext in Spring

While the beans package provides basic functionality for managing and manipulating beans, often in a programmatic way, the context package adds ApplicationContext, which enhances BeanFactory functionality in a more framework-oriented style. 

A bean factory is fine for simple applications, but to take advantage of the full power of the Spring Framework, you’ll probably want to load your application beans using Spring’s more advanced container, the application context.

Many users will use ApplicationContext in a completely declarative fashion, not even having to create it manually, but instead relying on support classes such as ContextLoader to automatically start an ApplicationContext as part of the normal startup process of a J2EE web-app. Of course, it is still possible to programmatically create an ApplicationContext.

The basis for the context package is the ApplicationContext interface, located in the org.springframework.context package. Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory. 



You could also implement your own ApplicationContext and add support for loading from other resources (such as a database). While many Contexts are available for loading beans, you’ll only need a few, which are listed below. The others are internal classes that are used by the framework itself.

1 )  ClassPathXmlApplicationContext: Loads context files from the classpath (that is, WEB-INF/classes or WEB-INF/lib for JARs) in a web application. Initializes using a 

                      new ClassPathXmlApplicationContext(path)
where path is the path to the file.


2 ) FileSystemXmlApplicationContext: Loads context files from the file system, which is nice for testing. Initializes using a
            new FileSystemXmlApplicationContext (path)
where path is a relative or absolute path to the file. The path argument can also be a String array of paths.

3. XmlWebApplicationContext: Loads context files internally by the ContextLoaderListener, but can be used outside of it. For instance, if you are running a container that doesn’t load Listeners in the order specified in web.xml, you may have to use this in another Listener. Below is the code to use this Loader.

XmlWebApplicationContext context = 
            new XmlWebApplicationContext();
context.setServletContext(ctx);
context.refresh();

Once you’ve obtained a reference to a context, you can get references to beans using  

   ctx.getBean(“beanId”)
You will need to cast it to a specific type, but that’s the easy part. Of the above contexts, ClassPathXmlApplicationContext is the most flexible. It doesn’t care where the files are, as long as they’re in the classpath. This allows you to move files around and simply change the classpath.



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

Aspect-Oriented Programming(AOP) in Spring - Part 1


Aspect-Oriented Programming (AOP) Introduction :
AOP is a new methodology that provides separation of crosscutting concerns by introducing a new unit of modularization—an aspect—that crosscuts other modules. With AOP you implement crosscutting concerns in aspects instead of fusing them in the core modules. An aspect weaver, which is a compiler-like entity, composes the final system by combining the core and crosscutting modules through a process called weaving.

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. 

AOP Fundamentals:
  • Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns.
    • Transaction management
    • Security
    • Logging
    • Auditing
    • Locking
  • AOP sometimes (partially) achieved via Decorators or Proxies
    • CORBA Portable Interceptors
    • Servlet Filters
  • Aspect : Implementation of a cross-cutting concern. 
  • Spring Advisors or Interceptors
  • Joinpoint : Execution point to target
    • Typically, methods
  • Advice : Action taken at a particular joinpoint.
  • Pointcut : A set of joinpoints specifying where advice should be applied (e.g. Regular expression)
  • Introduction/Mixin - Adding methods or fields to an advised class.
  • Weaving : Assembling aspects into advised objects.

Why use Dependency Injection in Spring?

What is Dependency Injection:
Originally, dependency injection was commonly referred to by another name inversion of control(IoC). 
In the Java community there's been a rush of lightweight containers that help to assemble components from different projects into a cohesive application.(Ex: Spring) Underlying these containers is a common pattern to how they perform the wiring, a concept they refer under the very generic name of "Inversion of Control"

For this new breed of containers the inversion is about how they lookup a plugin implementation. The approach that these containers use is to ensure that any user of a plugin follows some convention that allows a separate assembler module to inject the implementation into the lister.

Based on that revelation, he coined the phrase “dependency injection,” a term that better describes what is going on. Inversion of Control is a generic term and the more specific name for this pattern is Dependency Injection.

Dependency injection is basically giving an object what it needs instead of letting this object get it by itself. It is based on a best practice technique (design pattern). This technique allows a part of application to be changed without causing problems in other areas of the application. A design is inflexible unless it cannot be easily adapted.



Why use Dependency Injection:
        Instead of using Depenedency Injection if we hardcode "new" in our code.

  • What if something changes?
        How do we externalize configuration from Java code, important if things change?

By avoiding use of a custom factory we are reducing extra code to be written in the application

By applying Dependency Injection in your projects, you’ll find that your code will become significantly simpler, easier to understand, and easier to test.

Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally,
each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). This can lead to highly coupled and hard-to-test code. When applying Dependency injection(DI), objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects. So, DI means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

Software components (Clients), are often a part of a set of collaborating components which depend upon other components (Services) to successfully complete their intended purpose. In many scenarios, they need to know “which” components to communicate with, “where” to locate them, and “how” to communicate with them. When the way such services can be accessed is changed, such changes can potentially require the source of lot of clients to be changed.

One way of structuring the code is to let the clients embed the logic of locating and/or instantiating the services as a part of their usual logic. Another way to structure the code is to have the clients declare their dependency on services, and have some "external" piece of code assume the responsibility of locating and/or instantiating the services and simply supplying the relevant service references to the clients when needed. In the latter method, client code typically is not required to be changed when the way to locate an external dependency changes. This type of implementation is considered to be an implementation of Dependency Injection and the "external" piece of code referred to earlier is likely to be either hand coded or implemented using one of a variety of DI frameworks.

Dependency Injection uses the Hollywood Principle: “Don’t call me, I’ll call you.” In other words, your classes don’t look up or instantiate the classes they depend on. The control is inverted and some form of container sets the dependencies. Using IoC often leads to much cleaner code and provides an excellent way to de-couple dependent classes.



Benefits of Dependency Injection : 
  • Unit testable
  • Dependencies are explicit
  • Consistent
  • Can wire up arbitrarily complicated graphs
  • You don’t need to write plumbing code
  • Pluggability
  • Reduces cost of programming to interfaces to zero

Spring IoC setter Injection Example - Tutorial

Java bean calls :
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;
 }
}

ApplicationContext.xml
<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">
  <property name="message" value="Hello Friend, Welcome To Javastuff !!!! "/>
 </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());
 }
}

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

Spring Basic Bean Creation Example -Tutorial

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

Basic Bean Creation :

Lets start with a simple program about IoC. 
Spring IoC Bean class :


package com.javastuff.spring;

public class SpringExample {
 public String message = " Welcome to Javastuff ";

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

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

 
Spring IoC Container configuration file :
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" />

</beans>

Test Class :
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  :  Welcome to Javastuff 


    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.



    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