Thursday, September 21, 2017

Spring Life Cycle

Bean Life Cycle

1. The Bean Container finds the definition of the Spring Bean in the Configuration file.

2. The Bean Container creates an instance of the Bean using Java Reflection API.

3. If any properties are mentioned, then they are also applied. If the property itself is a Bean, then it is resolved and set.

4. If the Bean class implements the BeanNameAware interface, then the setBeanName() method will be called by passing the name of the Bean.

5. If the Bean class implements the BeanClassLoaderAware interface, then the method setBeanClassLoader() method will be called by passing an
    instance of the ClassLoader object that loaded this bean.
 
6. If the Bean class implements the BeanFactoryAware interface, then the method setBeanFactory() will be called by passing an instance of
BeanFactory  object.

7. If there are any BeanPostProcessors object associated with the BeanFactory that loaded the Bean, then the method
postProcessBeforeInitialization()   will be called even before the properties for the Bean are set.

8. If the Bean class implements the InitializingBean interface, then the method afterPropertiesSet() will be called once all the Bean properties
   defined in the Configuration file are set.
 
9. If the Bean definition in the Configuration file contains a 'init-method' attribute, then the value for the attribute will be resolved to a method
   name in the Bean class and that method will be called.
 
10.The postProcessAfterInitialization() method will be called if there are any Bean Post Processors attached for the Bean Factory object.

11. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the
    bean reference.
 
12. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean
    class will be called.


Spring framework provides following 4 ways for controlling life cycle events of bean:


1. InitializingBean and DisposableBean callback interfaces=>
InitalizingBean => void afterPropertiesSet() throws Exception;
DisposableBean =>  void destroy() throws Exception;

2. Other Aware interfaces for specific behavior=> 
BeanFactoryAware=>void setBeanFactory(BeanFactory beanFactory) throws BeansException
BeanNameAware =>void setBeanName(String name);
ApplicationContextAware =>void setApplicationContext(ApplicationContext applicationContext) throws BeansException


3. custom init() and destroy() methods in bean configuration file


4. @PostConstruct and @PreDestroy annotations


Spring BeanPost Processors

BeanPostProcessor Interface=>
postProcessBeforeInitialization()=> This method gets called before initialization
postProcessAfterInitialization ()=> This method gets called after the object is initialized


EmployeeBeanProcessor .java


/**
 *
 */
package com.bebo.component;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;


/**
 * @author anthakur
 *
 */
@Component
public class EmployeeBeanProcessor implements BeanPostProcessor {

/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
*/
@Override
public Object postProcessAfterInitialization(Object bean, String arg1) throws BeansException {
// TODO Auto-generated method stub
System.out.println("**********postProcessAfterInitialization**************"+bean);
return bean;
}

/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String arg1) throws BeansException {
// TODO Auto-generated method stub
System.out.println("************postProcessBeforeInitialization************"+bean);
return bean;
}

}


EmployeeUtility  .java


/**
 *
 */
package com.bebo.component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author anthakur
 *
 */
@Component
public class EmployeeUtility  implements InitializingBean, DisposableBean,BeanFactoryAware, BeanNameAware, ApplicationContextAware{


public void display() {
System.out.println("EmployeeUtility");
}

/* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("EmployeeUtility#afterPropertiesSet is invoked.....");

}

/* (non-Javadoc)
* @see org.springframework.beans.factory.DisposableBean#destroy()
*/
@Override
public void destroy() throws Exception {
System.out.println("EmployeeUtility#destroy is invoked.....");

}


/* (non-Javadoc)
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
// TODO Auto-generated method stub
System.out.println("EmployeeUtility#setApplicationContext  "+arg0);
}

/* (non-Javadoc)
* @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
*/
@Override
public void setBeanName(String arg0) {
// TODO Auto-generated method stub
System.out.println("EmployeeUtility#setBeanName  "+arg0);

}

/* (non-Javadoc)
* @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
*/
@Override
public void setBeanFactory(BeanFactory arg0) throws BeansException {
// TODO Auto-generated method stub
System.out.println("EmployeeUtility#setBeanFactory  "+arg0);

}

@PostConstruct
public void init(){
System.out.println("EmployeeUtility#init  ");

}

@PreDestroy
public void destroytext(){
System.out.println("EmployeeUtility#destroy  ");

}


}







Monday, September 18, 2017

Spring JDBC Example (XML and Annotation)

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringDemo1</groupId>
<artifactId>SpringDemo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<!-- repository for oracle -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>

<dependencies>
<!-- oracle ojdbc dependency -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>

</dependencies>
</project>

Employee.java


/**
 * 
 */
package com.bebo.model;

/**
 * @author anthakur
 *
 */
public class Employee {
private int id;
private String name;
private int salary;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


/**
* @return the id
*/
public int getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}


}

EmployeeService.java


/**
 * 
 */
package com.bebo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.bebo.dao.EmployeeDao;
import com.bebo.model.Employee;

/**
 * @author anthakur
 *
 */
@Service
public class EmployeeService {
@Autowired
private EmployeeDao employeeDao;

public void inserEmployee(Employee employee){
employeeDao.insertEmployee(employee);
}

public String getEmployeeName(int id) {
return employeeDao.getEmployeeName(id);
   }
}


EmployeeDao.java


/**
 * 
 */
package com.bebo.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.bebo.model.Employee;

/**
 * @author anthakur
 *
 */
@Repository
public class EmployeeDao {

@Autowired
private JdbcTemplate jdbcTemplate;

public void insertEmployee(Employee employee) {
jdbcTemplate.update("insert into employee(id,name,salary) values(?,?,?)", employee.getId(), employee.getName(),
employee.getSalary());
System.out.println("Successfully.....");
}

  public String getEmployeeName(int id) {
       String sql = "select name from employee where id = ?";
       String name = jdbcTemplate.queryForObject(sql,new Object[]{id},String.class);
       return name;
   }
  
}


AppConfig.java


/**
 * 
 */
package com.bebo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.bebo.dao.EmployeeDao;

/**
 * @author anthakur
 *
 */
@Configuration
@ComponentScan("com.bebo.*")
public class AppConfig {

@Bean
DriverManagerDataSource dataSource(){
DriverManagerDataSource dataSource =new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
dataSource.setUsername("ems");
dataSource.setPassword("ems");
return dataSource;
}
@Bean
JdbcTemplate jdbcTemplate(){
return new JdbcTemplate(dataSource());
}
}

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

<context:component-scan base-package="com.bebo.*"></context:component-scan>

<!-- <bean id="employee" class="com.bebo.Employee"> <property name="name" 
value="Anil Thakur"></property> <constructor-arg value="xyz" type="String"></constructor-arg> 
</bean> -->

<!-- <bean id="employeeDaoA" class="com.bebo.dao.EmployeeDao">
<property name="name" value="Anil Thakur from employeeDaoA"></property>
</bean>


<bean id="employeeDaoB" class="com.bebo.dao.EmployeeDao">
<property name="name" value="Anil Thakur from employeeDaoB"></property>
</bean> -->

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="ems" />
<property name="password" value="ems" />
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>

MainClass.java


/**
 * 
 */
package com.bebo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.bebo.config.AppConfig;
import com.bebo.model.Employee;
import com.bebo.service.EmployeeService;

/**
 * @author anthakur
 *
 */
public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {

/*
* Resource resource =new ClassPathResource("applicationContext.xml");
* BeanFactory beanFactory =new XmlBeanFactory(resource);
* Employee employee =(Employee) beanFactory.getBean("employee");
*/

/*ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");*/

AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

EmployeeService employeeService = (EmployeeService) applicationContext.getBean("employeeService");
Employee employee = new Employee();
employee.setId(2);
employee.setName("abc");
employee.setSalary(10000);
employeeService.inserEmployee(employee);
/* String name=employeeService.getEmployeeName(1);
System.out.println("Name="+name);*/

}

}


Tuesday, September 12, 2017

Spring Introduction and IOC


Spring

developed by Rod Johnson in 2003Spring Framework
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.



Advantages of Spring Framework

Predefined TemplatesLoose CouplingEasy to testLightweightFast DevelopmentPowerful abstractionDeclarative support


Modules:

Core, Beans, Context, Expression Language
AOP, Aspects and Instrumentation
Data Access / Integration
JDBC, ORM, OXM, JMS and Transaction modules.
Web, Web-Servlet, Web-Struts and Web-Portlet.
Spring batch








IoC Container

The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets informations from the XML file and works accordingly. 
The main tasks performed by IoC container are:
to instantiate the application classto configure the objectto assemble the dependencies between the objects


There are two types of IoC containers. They are:

BeanFactory

ApplicationContext
Resource resource=new ClassPathResource("applicationContext.xml");  BeanFactory factory=new XmlBeanFactory(resource);  

Bean Factory

Bean instantiation/wiring
Application ContextApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");      Bean instantiation/wiringAutomatic BeanPostProcessor registrationAutomatic BeanFactoryPostProcessor registrationConvenient MessageSource access (for i18n)ApplicationEvent publication

<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-4.0.xsd">   

Dependency Injection in Spring

Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled
Two ways to perform Dependency Injection in Spring framework
Spring framework provides two ways to inject dependency

By Constructor

<bean id="e" class="com.Employee">  <constructor-arg value="" type=""></constructor-arg>  </bean>  


By Setter method

<bean id="employee" class="com.bebo.Employee">  <property name="name" value="Anil Thakur"></property>  </bean>

Monday, September 11, 2017

Simple Spring Core Example using xml: Demo1

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Demo1</groupId>
  <artifactId>Demo1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>


</dependencies>
</project>

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

<bean id="employee" class="com.Employee">
<property name="name" value="Anil Thakur"></property>
</bean>

</beans>


Employee.java


public class Employee {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void display(){
   System.out.println("Hello: "+name);
}
}


MainClass.xml

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class MainClass {

public static void main(String [] args){
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory beanFactory =new XmlBeanFactory(resource);

Employee employee =(Employee) beanFactory.getBean("employee");
employee.display();


}
}

Tuesday, May 23, 2017

Spring Email Example

SpringEmailDemo



pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringEmailDemo</groupId>
<artifactId>SpringEmailDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

<properties>
<java.version>1.8</java.version>
<javax.mail.version>1.4</javax.mail.version>
<spring-framework.version>4.3.8.RELEASE</spring-framework.version>
</properties>

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

</dependencies>

</project>

application-context.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.masterjee"></context:component-scan>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="25" />
<property name="username" value="email@gmail.com" />
<property name="password" value="password" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
</beans>

EmailService .java

package com.masterjee;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    @Autowired
    private MailSender mailSender;

    public void sendEmail(String to, String subject, String body) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);

    }
}

MainClass .java

package com.masterjee;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
        EmailService emailService = (EmailService) context.getBean("emailService");
        emailService.sendEmail("anil.kamrou@gmail.com", "Greeting ", "This email is from my application !!");

        // close context
        ((ClassPathXmlApplicationContext) context).close();

    }

}


Thursday, May 18, 2017

Spring Bean Life Cycle Example



pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringBeanLifeCycle</groupId>
<artifactId>SpringBeanLifeCycle</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<spring-framework.version>4.3.8.RELEASE</spring-framework.version>
</properties>

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

</dependencies>
</project>

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

<bean id="user" class="com.masterjee.User" />
<bean id="userService" class="com.masterjee.UserService">
<property name="user" ref="user" />
</bean>
<bean id="myService" class="com.masterjee.MyService" />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
</beans>

User.java

package com.masterjee;

public class User {
    private int id;
    private String name;
    private String email;
    private String contact;
    private String password;
    private String passwordConfirm;

    public User(){
        System.out.println("Creating User instance");
    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getPasswordConfirm() {
        return passwordConfirm;
    }

    public void setPasswordConfirm(String passwordConfirm) {
        this.passwordConfirm = passwordConfirm;
    }

}

UserService.java

package com.masterjee;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class UserService {
    private User user;

    @PostConstruct
    public void init() {
        System.out.println("init method of UserService using @PostConstruct");
        this.user.setName("Anil");
    }

    public UserService() {
        System.out.println("creating instance of UserService");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("destroy method of UserService using @PreDestroy");
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}

MyService.java

package com.masterjee;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class MyService {
    @PostConstruct
    public void init() {
        System.out.println("init method of UserService using @PostConstruct");
    }

    public MyService() {
        System.out.println("creating instance of UserService");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("destroy method of UserService using @PreDestroy");
    }

}

MainClass.java

package com.masterjee;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {

    public static void main(String[] args) {

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("Spring Context started");
        UserService userService = (UserService) applicationContext.getBean("userService");
        System.out.println("Bean received from application context");
        System.out.println("name: "+userService.getUser().getName());
        applicationContext.close();
        System.out.println("Spring Context closed");
    }

}

Console

May 18, 2017 5:26:18 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Thu May 18 17:26:18 IST 2017]; root of context hierarchy
May 18, 2017 5:26:18 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Creating User instance
creating instance of UserService
init method of UserService using @PostConstruct
creating instance of UserService
init method of UserService using @PostConstruct
Spring Context started
Bean received from application context
name: Anil
May 18, 2017 5:26:19 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Thu May 18 17:26:18 IST 2017]; root of context hierarchy
destroy method of UserService using @PreDestroy
destroy method of UserService using @PreDestroy
Spring Context closed

Thursday, September 3, 2015

IoC Container

IoC Container

There are two types of IoC containers. 
  1. BeanFactory
  2. ApplicationContext
  • to instantiate the application class
  • to configure the object
  • to assemble the dependencies between the objects

BeanFactory and the ApplicationContext

The org.springframework.beans.factory.BeanFactory org.springframework.context.ApplicationContext interfaces acts as the IoC container.

The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.

Using BeanFactory

Resource resource=new ClassPathResource("applicationContext.xml");  
BeanFactory factory=new XmlBeanFactory(resource);  

Using ApplicationContext

ApplicationContext context =   
    new ClassPathXmlApplicationContext("applicationContext.xml");

Dependency Injection in Spring

Dependency Injection (DI) is a design pattern that removes the dependency from the programming
code so that it can be easy to manage and test the application. Dependency Injection makes our
programming code loosely coupled. To understand the DI better, Let's understand the Dependency Lookup (DL) first:

Dependency Lookup
A obj = new AImpl();
A obj = A.getA();

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup("java:comp/env");
A obj = (A)environmentCtx.lookup("A");

Problems of Dependency Lookup

  • tight coupling
  • Not easy for testing

Dependency Injection

Spring framework provides two ways to inject dependency
  • By Constructor
  • By Setter method

Examples