Powered by Blogger.
Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Thursday, 12 June 2014

Loose coupling in Spring

How to create a loosely coupled Java application using Spring Frameworks Dependency Injection ?

Let see First tightly coupled

public interface Animal {
       public void makeNoise();
}

public class Dog implements Animal {
       @Override
       public void makeNoise() {
              System.out.println("Dog is barking");
       }
}

public class Lion implements Animal {
       @Override
       public void makeNoise() {
              System.out.println("Lion is roaring");
       }
}

public class AnimalService {
       private Animal animal= new Dog();
       public void makeSound(){
              animal.makeNoise();
       }
}

public class AnimalTest {
       public static void main(String[] args) {
              AnimalService animalService = new AnimalService();
              animalService.makeSound();
       }
}


As in service new operator is used. So in future if we want to change from to Lion, we need to modify the java code.

Let’s see loose coupling

There is little changes in AnimalService & AnimalTest.
public class AnimalService {
       private Animal animal;
       public void setAnimal(Animal animal) {
              this.animal = animal;
       }

       public void makeSound() {
              animal.makeNoise();
       }
}
public class AnimalTest {
       public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
AnimalService animalService = (AnimalService) context.getBean("animalService");
              animalService.makeSound();

       }

}
applicationContext.xml
<bean id="dog" class="com.shambhu.model.Dog" />
<bean id="lion" class="com.shambhu.model.Lion" />
<bean id="animalService" class="com.shambhu.service.AnimalService">
       <property name="animal" ref="dog" />
</bean>

As in AnimalService there is no new oper
AS in Animal service there is no new operator just configured in xml, where we can change ref, with out touching java we can make ref dog to lion.



Friday, 6 June 2014

BeanPostProcessor , init-method & destroy-method

Use of init-method and destroy-method attributes in bean definition

Spring container can be configured to look for these initialization and destroy callback method names on the bean. In order to do so, it needs to find the init-method and destroy-method elements inside the bean definition. Thus, the named callback methods will be invoked.

The HelloWorld bean now has two methods, initIt() and cleanUp() that print a message.

Xml.Configuration

<bean id="messanger" class="com.bean.HelloWorld" init-method="initIt" destroy-method="cleanUp">
      <property name="msg" value="Hello World" />

</bean>

Bean Definition
public class HelloWorld  implements BeanPostProcessor{
       private String msg;

       public String getMsg() {
              return msg;
       }

       public void setMsg(String msg) {
              this.msg = msg;
       }

       @Override
       public Object postProcessBeforeInitialization(Object bean, String beanName)
                     throws BeansException {
               System.out.println("BeforeInitialization : " + beanName);
              return bean;
       }

       @Override
       public Object postProcessAfterInitialization(Object bean, String beanName)
                     throws BeansException {
               System.out.println("ProcessAfterInitialization : " + beanName);
              return bean;
       }

       public void initIt() {
               System.out.println("Bean is going through init.");
       }

       public void cleanUp() {
              System.out.println("Bean will destroy now.");
       }
 }


Testing

public class HelloMain {

  public static void main(String[] args) {
     AbstractApplicationContext context = new 
                      ClassPathXmlApplicationContext("spring-beans.xml");
     HelloWorld obj = (HelloWorld) context.getBean("messanger");
     System.out.println(obj.getMsg());
     context.registerShutdownHook();
  }
}



output

Jun 07, 2014 12:05:15 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@75cfa3d2: startup date [Sat Jun 07 00:05:15 IST 2014]; root of context hierarchy
Jun 07, 2014 12:05:15 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-beans.xml]
Bean is going through init.
BeforeInitialization : test
ProcessAfterInitialization : test
Hello World
Bean will destroy now.


Another easy way for initialization and destroy method callbacks without the use of Spring-specific InitializingBean andDisposableBean callback interfaces



public class HelloWorldBeanPostProcessor implements InitializingBean,DisposableBean  {

       @Override
       public void destroy() throws Exception {
              System.out.println("Bean will destroy now.");
       }

       @Override
       public void afterPropertiesSet() throws Exception {
              System.out.println("Bean is going through init.");
       }
}


BeanNameAware and BeanFactoryAware

BeanNameAware and BeanFactoryAware


The first one makes the object aware of their bean name in a bean factory.
The second interface gives the bean access to the Bean Factory that created it.


  1. The xxxAware interface is a common pattern used within the Spring framework. They are typically used to allow a Spring managed bean to be given an object (via the interfaces setXxx method) at Spring bootstrap time.
  2. Springs documentation says this about the Aware interface, which is a super interface to the two you mention:
  3. Marker superinterface indicating that a bean is eligible to be notified by the Spring container of a particular framework object through a callback-style method.

public class HelloWorld  implements BeanNameAware, BeanFactoryAware{
       private String msg;

       public String getMsg() {
              return msg;
       }

       public void setMsg(String msg) {
              this.msg = msg;

       }

       @Override
       public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
               System.out.println("received the beanFactory " + beanFactory);
             
       }

       @Override
       public void setBeanName(String name) {
               System.out.println("the name of the bean is " + name);
             

       }
}

Bean definition


<bean id="messanger" class="com.shambhu.bean.HelloWorld">
      <property name="msg" value="Hello World" />

</bean>

Testing

public class HelloMain {
    public static void main(String[] args) {
ApplicationContext beanFactory = new ClassPathXmlApplicationContext(
                           "spring-beans.xml");
        HelloWorld messanger = (HelloWorld) beanFactory.getBean("messanger");
        System.out.println(messanger.getMsg());
    }
}

OutPut

Jun 06, 2014 11:22:52 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7dbc345a: startup date [Fri Jun 06 23:22:52 IST 2014]; root of context hierarchy
Jun 06, 2014 11:22:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-beans.xml]
the name of the bean is messanger
received the beanFactory org.springframework.beans.factory.support.DefaultListableBeanFactory@71a7cdd0: defining beans [messanger]; root of factory hierarchy
Hello World



Spring Start Program

Bean

public class HelloWorld {
     private String msg;
      public String getMsg() {
           return msg;
     }
     public void setMsg(String msg) {
            this.msg = msg;
      }
}

spring-beans.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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

      <bean id="messanger" class="com.shambhu.bean.HelloWorld">
        <property name="msg" value="Hello World" />
       </bean>
</beans>

Testing

public class HelloMain {


public static void main(String[] args) {
       ApplicationContext beanFactory = new  ClassPathXmlApplicationContext("spring-beans.xml");
        HelloWorld messanger= (HelloWorld) beanFactory.getBean("messanger");
        System.out.println(messanger.getMsg());
}
}




pom.xml
<properties>
<spring.version>4.0.3.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>

Jun 06, 2014 10:40:38 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4f114133: startup date [Fri Jun 06 22:40:38 IST 2014]; root of context hierarchy
Jun 06, 2014 10:40:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-beans.xml]
Hello World


Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP