Wednesday, September 27, 2017

Spring MVC

The DispatcherServlet

The DispatcherServlet
DispatcherServlet class works as the front controller. It is responsible to manage the flow of the spring mvc application.

The @Controller annotation is used to mark the class as the controller

The @RequestMapping annotation is used to map the request url




dispacher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd ">

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

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

<mvc:annotation-driven />

</beans>



web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<display-name>Demo2</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>


dispatcher-servlet.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"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

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

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

<mvc:annotation-driven />

</beans>


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">

</beans>



EmployeeController .java


/**
 * @author Anil.Thakur
 *
 */
@Controller
public class EmployeeController {

@RequestMapping(value = "/")
    public ModelAndView index() {
System.out.println("*********index******");
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index");
        return mav;
    }
@RequestMapping("greeting")
public ModelAndView helloWorld(){
System.out.println("***************");
        String message = "HELLO SPRING MVC";  
        return new ModelAndView("welcome", "message", message);
}
}


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>Demo2</groupId>
<artifactId>Demo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.version>4.0.2.RELEASE</spring.version>
<servlet.api.version>2.5</servlet.api.version>
<jsp.api.version>2.2</jsp.api.version>
<jstl.version>1.2</jstl.version>
<oracle.version>11.2.0.3</oracle.version>
</properties>
<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>${oracle.version}</version>
</dependency>

<!-- servlet dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.api.version}</version>
</dependency>


<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>


<!-- jstl dependency -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>


<!-- Spring dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- All Mail related stuff + Much more -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>

Monday, September 25, 2017

Spring AOP

AOP concepts


Aspect: a modularization of a concern that cuts across multiple classes.
Transaction management is a good example of a crosscutting concern in enterprise Java applications.
In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or
regular classes annotated with the @Aspect annotation (the @AspectJ style).

Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception.
In Spring AOP, a join point always represents a method execution.

Advice: action taken by an aspect at a particular join point.
Different types of advice include "around," "before" and "after" advice.
(Advice types are discussed below.) Many AOP frameworks, including Spring, model an advice as an interceptor,
maintaining a chain of interceptors around the join point.

Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and
runs at any join point matched by the pointcut (for example, the execution of a method with a certain name).
The concept of join points as matched by pointcut expressions is central to AOP, and
Spring uses the AspectJ pointcut expression language by default.

Types of advice:
Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

After returning advice: Advice to be executed after a join point completes normally:
for example, if a method returns without throwing an exception.

After throwing advice: Advice to be executed if a method exits by throwing an exception.

After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Annotation on Aspect Class 
@AspectJ


All advice Annotation
@Around
@After
@Before
@AfterReturning
@AfterThrowing

ForExample

@Before("execution(* com.bebo.dao.EmployeeDao.*(..))")

pom.xml

<!-- Spring AOP + AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.12</version>
</dependency>

EmployeeAspect .java

/**
 * @author anthakur
 *
 */
@Aspect
public class EmployeeAspect {

@After("execution(* com.bebo.dao.EmployeeDao.*(..))")
public void DisplayOnInsertEmployee(JoinPoint joinPoint){
System.out.println(" EmployeeDao method is invoked...."+joinPoint.getThis());
}

}

AppConfig.java

@EnableAspectJAutoProxy
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

@Bean
EmployeeAspect employeeAspect(){
return new EmployeeAspect();
}
}



Example: AspectEmployee.java


package com.bebo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class AspectEmployee {

    @Before("execution(* com.bebo.service.EmployeeService.*(..))")
    public void logServiceMethod(JoinPoint joinPoint){
        System.out.println("logServiceMethod loging the info for"+joinPoint.getSignature().getName());
       
    }
    @After("execution(* com.bebo.service.EmployeeService.*(..))")
    public void logServiceMethodAfterAfter(JoinPoint joinPoint){
        System.out.println("logServiceMethodAfterAfter loging the info for"+joinPoint.getSignature().getName());
       
    }
   
    @Around("execution(* com.bebo.service.EmployeeService.*(..))")
    public void logServiceMethodAfterAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("logServiceMethodAfterAround loging the info for"+joinPoint.getSignature().getName());
        joinPoint.proceed();
    }
   

    @AfterReturning("execution(* com.bebo.service.EmployeeService.*(..))")
    public void logServiceMethodAfterAfterReturning(JoinPoint joinPoint){
        System.out.println("logServiceMethodAfterAfterReturning loging the info for"+joinPoint.getSignature().getName());
       
    }
   
    @AfterThrowing("execution(* com.bebo.service.EmployeeService.*(..))")
    public void logServiceMethodAfterExpection(JoinPoint joinPoint){
        System.out.println("logServiceMethodAfterExpection loging the info for"+joinPoint.getSignature().getName());
       
    }

}




Thursday, September 21, 2017

Add Properties File using Spring


Annotation : @Value


@Value("${jdbc.driverClassName}")     // Pass key using exp. Language
private String driverClassName;


Add Resource Path:

@PropertySource("classpath:/application.properties")

<context:property-placeholder location="classpath:/application.properties"/>

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();


}
}