Tuesday, February 13, 2018

Bean Scope


singleton

  • Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

  • Scopes a single bean definition to any number of object instances.

request

  • Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

  • Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session

  • Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

bean factory, Bean Injection,

What is a bean factory?


Often seen as an ApplicationContext
BeanFactory is not used directly often
ApplicationContext is a complete superset of bean factory methods
Same interface implemented
Offers a richer set of features
Spring uses a BeanFactory to create, manage and locate “beans” which are basically instances of a class
Typical usage is an XML bean factory which allows configuration via XML files


How are beans created?


Beans are created in order based on the dependency graph
Often they are created when the factory loads the definitions
Can override this behavior in bean

<bean class=“className” lazy-init=“true” />

You can also override this in the factory or context but this is not recommended
Spring will instantiate beans in the order required by their dependencies
app scope singleton - eagerly instantiated at container startup
lazy dependency - created when dependent bean created
VERY lazy dependency - created when accessed in code

How are beans injected?


A dependency graph is constructed based on the various bean definitions
Beans are created using constructors (mostly no-arg) or factory methods
Dependencies that were not injected via constructor are then injected using setters
Any dependency that has not been created is created as needed

Multiple bean config files


There are 3 ways to load multiple bean config files (allows for logical division of beans)
Load multiple config files from web.xml

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/WEB-INF/spring-config.xml, classpath:/WEB-INF/applicationContext.xml</param-value>
</context-param>

Use the import tag


<import resource="services.xml"/>

Load multiple config files using Resources in the application context constructor

Recommended by the spring team

Not always possible though
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext-part2.xml"});

Bean properties?

The primary method of dependency injection

Can be another bean, value, collection, etc.

<bean id="exampleBean" class="org.example.ExampleBean">
       <property name="anotherBean">
    <ref bean="someOtherBean" />
       </property>
</bean>

This can be written in shorthand as follows

<bean id="exampleBean" class="org.example.ExampleBean">
       <property name="anotherBean" ref="someOtherBean" />
</bean>

Monday, February 12, 2018

Bean and Bean definition

What is a bean?


Typical java bean with a unique id
In spring there are basically two types
  • Singleton
One instance of the bean created and referenced each time it is requested
  • Prototype (non-singleton)
New bean created each time
Same as new ClassName()


What is a bean definition?

Defines a bean for Spring to manage

Key attributes

  • class (required): fully qualified java class name
  • id: the unique identifier for this bean
  • configuration: (singleton, init-method, etc.)
  • constructor-arg: arguments to pass to the constructor at creation time
  • property: arguments to pass to the bean setters at creation time
  • Collaborators: other beans needed in this bean (a.k.a dependencies), specified in property or constructor-arg
Typically defined in an XML file

Sample bean definition


<bean id="exampleBean" class=”org.example.ExampleBean">
   <property name="beanOne"><ref bean="anotherExampleBean"/></property>
   <property name="beanTwo"><ref bean="yetAnotherBean"/></property>
   <property name="integerProperty"><value>1</value></property>
</bean>

public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
    this.beanOne = beanOne; }
public void setBeanTwo(YetAnotherBean beanTwo) {
    this.beanTwo = beanTwo; }
public void setIntegerProperty(int i) {
    this.i = i; }

}

Spring Setter and Constructor Injection Example

Setter Injection

Employee.java


/**
 * @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;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
    }
   
}

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>
    <context:property-placeholder location="classpath:/application.properties"/>

    <bean id="employee" class="com.bebo.model.Employee">
        <property name="id" value="1">      </property> 
         <property name="name" value="Anil Thakur">      </property> 
        <property name="salary" value="100">      </property> 
       
      </bean>
</beans>


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>SpringDemo2</groupId>
  <artifactId>SpringDemo2</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>


 <dependencies>


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


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

MainClass.java

/**
 *
 */
package com.bebo;

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;

import com.bebo.model.Employee;

/**
 * @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");
         System.out.println(employee.toString());
        }
}

Constructor Injection

pom.xml will be same

MainClass.java will be same


In ApplicationContext.xml

    <bean id="employee" class="com.bebo.model.Employee">
        <constructor-arg value="1" ></constructor-arg>
         <constructor-arg name="name" value="Anil" ></constructor-arg>
          <constructor-arg value="100" ></constructor-arg>      

    </bean>


Output

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Employee [id=1, name=Anil, salary=100]

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