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

Spring AOP - Before Advice Example With @Before Annotation

In this tutorial, we will show you a step by step example declaring before advice with @Before annotation using Spring AOP and @AspectJ annotation style. Before advice is executed before join point but which does not have an ability to prevent execution flow proceeding to the join point. In Spring AOP, join point always represents a method execution.

Spring Security - Tutorial With Example

In this spring security tutorial and example, we will create a basic login authentication example that comes with spring security. This tutorial will focus on the security configuration using Spring Security 3.1. 

Spring MVC Form Validation Tutorial and Example

This tutorial walks you through the step by step instructions in order to support and apply validation example in Spring MVC. Please see Spring MVC Hello World Example to setup spring MVC environment.

Spring Data Redis - JRedis Hello World Example

In this tutorial, we will show you an example how to integrate and use redis data store (which is a NoSQL  Key Value data store) with Spring Data. At the end of this Hello World example, you will be able to write CRUD operations with Spring data Redis based applications.

Redis is an open source, advanced key-value data store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. Spring Data for Redis is part of the umbrella Spring Data project which provides support for writing Redis applications. This example uses a JRedis, a specification and reference implementation of Redis

Spring Data MongoDB - Hello World Example

In this tutorial, we will show how to configure MongoDB using Spring Data. And then we will create hello world example to show how to perform CRUD operations with MongoDB and Spring Data. 

In order to run this example, you would need to install mongodb and follow the instructions and would need to have following tools and libraries.

File Upload (multiplart) Example Using Spring

In this article, we will demonstrate a step by step example of how to upload a file using Spring and multiplart request. Spring has built-in multipart support to handle fileuploads in web applications. The design for the multipart support is done with pluggable MultipartResolver objects, defined in the org.springframework.web.multipart package. Out of the box, Spring provides a MultipartResolver for use with Commons FileUpload  http://jakarta.apache.org/commons/fileupload). How uploading files is supported will be described here.

How to Send E-mail using Spring and JavaMail

In this article, we will show you an example that will demonstrate how to send e-email using Spring and JavaMail. The following additional jars to be on the classpath of your application in order to be able to use the Spring Framework's email library.
  • The JavaMail mail.jar library
  • The JAF activation.jar library
The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client.

Spring MVC Internationalization (i18n) Tutorial & Example

This tutorial walks you through the step by step instructions in order to support internationalization (i18n) in Spring MVC. Please see Spring MVC Web Application With Example to setup Spring MVC basic example. 

Spring MVC Tutorial - Create Hello World Example


In this tutorial, we will create a small web application using Spring MVC hello world example to show how to setup and develop Spring MVC based applications. See Setup development environment using Eclipse and Tomcat article in order to setup development environment for Spring MVC using eclipse and tomcat.

Spring's web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central servlet that dispatches requests to controllers and offers other functionality facilitating the development of web applications.

Job Scheduling Example using Simple Trigger in Spring


The Spring Framework features integration classes for scheduling support. Currently, Spring supports the Quartz Scheduler (http://www.opensymphony.com/quartz/). Schedulers are set up using a FactoryBean with optional references to Trigger instances.

@Required Annotation Example in Spring



The @Required annotation applies to bean property setter methods, as in the following example:

    public class SimpleMovieLister {
         private MovieFinder movieFinder;
        @Required
       public void setMovieFinder(MovieFinder movieFinder) {
            this.movieFinder = movieFinder;
       }
   }


This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on. Note that it is still recommended to put assertions intothe bean class itself (for example into an init method) in order to enforce those required references and values even when using the class outside of a container.

Build RESTful Web Services using Spring


Spring, the well-known framework for building Java EE applications, now supports REST in its MVC layer. This article introduces the "Spring way" to build RESTful web services. Learn how to use Spring APIs and annotations to build RESTful web services, and see how Spring integrates this new feature seamlessly into its original framework. This article assumes that reader has basic understanding of RESTful web service concept, Eclipse and Tomcat.

Server Example using Spring REST Support

1. Enable Spring WebApplicationContext in WEB-INF/web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
 <display-name>Archetype Created Web Application</display-name>
 <servlet>
  <servlet-name>rest</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
      <init-param>
      <param-name>config-api</param-name>
      <param-value>WEB-INF/rest-servlet.xml</param-value>
    </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>rest</servlet-name>
  <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
</web-app>
 

2. Set up the Spring MVC-related configuration (Controller, View, View Resolver,Message Converters) in the WEB-INF/rest-servlet.xml file. Following shows the most important snippet.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  <context:annotation-config />
  
 <context:component-scan base-package="com.mycompany.mywebapp" />
 <bean
  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
   <list>
    <ref bean="marshallingHttpMessageConverter" />
   </list>
  </property>
 </bean>


 <bean id="marshallingHttpMessageConverter"
  class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
  <property name="marshaller" ref="jaxbMarshaller" />
  <property name="unmarshaller" ref="jaxbMarshaller" />
 </bean>
 <bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
  <property name="classesToBeBound">
   <list>
    <value>com.mycompany.mywebapp.HelloWorldRequest
    </value>
    <value>com.mycompany.mywebapp.HelloWorldResponse
    </value>

   </list>
  </property>
 </bean>

 <bean id="helloWorldResponseView"
  class="org.springframework.web.servlet.view.xml.MarshallingView">
  <constructor-arg ref="jaxbMarshaller" />
 </bean>

 <bean
  class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
   <map>
    <entry key="xml" value="application/xml" />
    <entry key="html" value="text/html" />
   </map>
  </property>
  <property name="viewResolvers">
   <list>
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />

   </list>
  </property>
 </bean>

</beans>
 

In the code above:

Component-scan
    Enables automatic scan for the class that has Spring annotations In practice, it's used to detect the @Controller annotation defined in controller classes.

AnnotationMethodHandlerAdapter
    Bean that will make the @ReqeustMapping annotation on the class or method to be processed by Spring.

Jaxb2Mashaller
    Defines the marshaller/unmarshaller that uses JAXB 2 to do the object XML mapping (OXM)

MashallingView
     Defines an XML representation view that utilizes the Jaxb2Mashaller

BeanNameViewResolver
    Defines a view resolver using the bean name that the user specifies.
    The example will use the MarshallingView name "helloWorldResponseView."

That completes the Spring-related configuration.
 

3. The next step is to write a controller that handles the user request, HelloWorldRequest and HelloWorldResponse. Following shows all classes.

######### HelloWorld Request Class ##########
        
package com.mycompany.mywebapp;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="helloWorldRequest")
public class HelloWorldRequest {
 private String helloString;

 public String getHelloString() {
  return helloString;
 }

 public void setHelloString(String helloString) {
  this.helloString = helloString;
 }
 
}

      ######### HelloWorld Response Class ##########


package com.mycompany.mywebapp;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="helloWorldResponse")
public class HelloWorldResponse {
 private String helloString;

 public String getHelloString() {
  return helloString;
 }

 public void setHelloString(String helloString) {
  this.helloString = helloString;
 }
}

   ######### HelloWorld Controller Class ##########
package com.mycompany.mywebapp;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class HelloWorldController {
 
 @RequestMapping(method=RequestMethod.POST,value="/postHelloWorld")
 public ModelAndView handlePostRequest(@RequestBody HelloWorldRequest helloWorldRequest){
  String request = helloWorldRequest.getHelloString();
  String response = "Hello " + request;
  HelloWorldResponse helloWorldResponse= new HelloWorldResponse();
  helloWorldResponse.setHelloString(response);
  return new ModelAndView("helloWorldResponseView", "helloWorldResponse", helloWorldResponse);
 }
 
 
 @RequestMapping(method=RequestMethod.GET,value="/getHelloWorld/{request}")
 public ModelAndView handlePostRequest(@PathVariable String request){
  String response = "Hello " + request;
  HelloWorldResponse helloWorldResponse= new HelloWorldResponse();
  helloWorldResponse.setHelloString(response);
  return new ModelAndView("helloWorldResponseView", "helloWorldResponse", helloWorldResponse);
 }
}
 

Clients that communicate with REST services

1. Create resources directory under src/main folder and make it a source folder. Configure client-context.xml under this resources directory as below

<?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-3.0.xsd">

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                    <property name="marshaller" ref="jaxbMarshaller" />
                    <property name="unmarshaller" ref="jaxbMarshaller" />
                </bean>
                
            </list>
        </property>
    </bean>

    <bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
              <value>com.mycompany.wsclient.HelloWorldRequest</value>
                <value>com.mycompany.wsclient.HelloWorldResponse</value>
             </list>
        </property>
    </bean>
</beans>
 

2. Create 'HelloWorldRequest' and 'HelloWorldResponse' objects under com.mycompany.wsclient package as created in Step#5 in server part

3. Create WSClient as shown below.

package com.mycompany.wsclient;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.client.RestTemplate;


/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
     System.out.println( "Hello World!" );
     ApplicationContext ctx = new ClassPathXmlApplicationContext("client-context.xml");
     RestTemplate restTemplate = (RestTemplate)ctx.getBean("restTemplate");
     
     /*  GET REQUEST */
     Map <String,String> parameters = new HashMap<String,String>();
     parameters.put("request", "RESTful WebService");
     
     HelloWorldResponse helloWorldResponse = restTemplate.getForObject("http://localhost:8080/mywebapp/rest/getHelloWorld/{request}", HelloWorldResponse.class,parameters);
     System.out.println(helloWorldResponse.getHelloString());
     
     /* POST REQUEST*/
     HelloWorldRequest helloWorldRequest = new HelloWorldRequest();
     helloWorldRequest.setHelloString("RESTful WebService");
     helloWorldResponse = restTemplate.postForObject("http://localhost:8080/mywebapp/rest/postHelloWorld", helloWorldRequest,HelloWorldResponse.class);
     System.out.println(helloWorldResponse.getHelloString());
    }
}
 

AOP : Examples of Common Pointcut Expressions


Some examples of common pointcut expressions in Aspect Oriented Programming (AOP) are given below.

• the execution of any public method:

  execution(public * *(..))

• the execution of any method with a name beginning with "set":

  execution(* set*(..))

• the execution of any method defined by the AccountService interface:

  execution(* com.xyz.service.AccountService.*(..))

• the execution of any method defined in the service package:

  execution(* com.xyz.service.*.*(..))

• the execution of any method defined in the service package or a sub-package:

  execution(* com.xyz.service..*.*(..))

• any join point (method execution only in Spring AOP) within the service package:

  within(com.xyz.service.*)

• any join point (method execution only in Spring AOP) within the service package or a sub-package:

  within(com.xyz.service..*)

• any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface:

  this(com.xyz.service.AccountService)

• any join point (method execution only in Spring AOP) where the target object implements the
AccountService interface:

  target(com.xyz.service.AccountService)

• any join point (method execution only in Spring AOP) which takes a single parameter, and where the argument passed at runtime is Serializable:

  args(java.io.Serializable)


Note that the pointcut given in this example is different to execution(* *(java.io.Serializable)): the args version matches if the argument passed at runtime is Serializable, the execution version matches if the method signature declares a single parameter of type Serializable.


• any join point (method execution only in Spring AOP) where the target object has an @Transactional annotation:

  @target(org.springframework.transaction.annotation.Transactional)

• any join point (method execution only in Spring AOP) where the declared type of the target object has an @Transactional annotation:

  @within(org.springframework.transaction.annotation.Transactional)

• any join point (method execution only in Spring AOP) where the executing method has an @Transactional

  @annotation(org.springframework.transaction.annotation.Transactional)

• any join point (method execution only in Spring AOP) which takes a single parameter, and where the runtime type of the argument passed has the @Classified annotation:

  @args(com.xyz.security.Classified)

• any join point (method execution only in Spring AOP) on a Spring bean named 'tradeService':

  bean(tradeService)

• any join point (method execution only in Spring AOP) on Spring beans having names that match the wildcard expression '*Service':

 bean(*Service)

Spring Aspect (AOP) Example with XML based Configuration


Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.) This tutorial demonstrate an example to configure an aspect with the help of XML or Schema. Please see AOP with annotation example link for the example using @AspectJ annotation. 

Following jars (over and above your existing setup) will be needed in the classpath in order to execute the examples.

aspectjrt-1.6.8.jar
aspectjweaver-1.6.8.jar 
spring-aop-3.0.5.RELEASE.jar
spring-aspects-3.0.5.RELEASE.jar


Service Class

Let's create a sample service class on which an aspect will be applied.

package com.mycompany.service;
    public class MyService {
        public void doService() {
            System.out.println("my service is called");
        }
}
}

Aspect Class

Let's create a sample aspect class.


package com.mycompany.aspect;
    public class MyAspect {        
        public void doLog(){
            System.out.println("do logging");
        }        
        public void doSysout(){
            System.out.println("do sysout");
        }
    }

XML Configuration File

Following is the Spring XML or Schema way of configuring the aspects. Here doLog method of MyAspect will be called before doService is executed and doSysout method will be called after doService is executed.

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

 <aop:config>
  <aop:pointcut expression="execution(* com.mycompany.service.MyService.*(..))"
   id="theBeforeExecutionOfSomeMyServiceMethod" />
  <aop:aspect ref="myAspect">
   <aop:before pointcut-ref="theBeforeExecutionOfSomeMyServiceMethod"
    method="doLog" />
   <aop:after method="doSysout" pointcut-ref="theBeforeExecutionOfSomeMyServiceMethod" />
  </aop:aspect>
 </aop:config>
 <bean id="myAspect" class="com.mycompany.aspect.MyAspect"/>
</beans>

Please see Examples of common pointcut expressions link to see examples of common pointcut expressions.
    
    

    Spring Aspect (AOP) Example with @AspectJ Annotation

    This article demonstrates the example of Aspect Oriented Programming (AOP) using @AspectJ annotation in Spring. Please click Spring AOP Example with XML Configuration to see the example of the same using XML or Schema style. At the end of this tutorial, you will be able to apply various aspects on your service methods. 

    Following jars (over and above your existing setup) will be needed in the classpath in order to execute the examples.
    aspectjrt-1.6.11.jar
    aspectjweaver-1.6.11.jar
    aopalliance-1.0.jar
    cglib-nodep-2.1_3.jar
    commons-logging-1.1.1.jar
    spring-aop-3.0.5.RELEASE.jar
    spring-aspects-3.0.5.RELEASE.jar
    
    
    Service Class
    
    
    Let's create a sample service class on which Aspect will be applied.
    
    
    package com.mycompany.myapp.service;
    
    public class MyService {
        public void doService() {
            System.out.println("my service is called");
        }
    }
    
    Aspect Class
    
    
    Let's create a sample Aspect Class. Please see Examples of common pointcut expressions link to see examples of common pointcut expressions.
    package com.mycompany.myapp.aspect;
    
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    
    @Aspect
    public class MyAspect {
    
     // Before Pointcut This method will be called before any method in MyService
     // is executed
     @Before("execution(* com.mycompany.myapp.service.MyService.*(..))")
     public void doLog() {
      System.out.println("do logging");
     }
    
     // After pointcut This method will be called after any method in MyService
     // is executed
     @After("execution(* com.mycompany.myapp.service.MyService.*(..))")
     public void doSysout() {
      System.out.println("do sysout");
     }
    }

    Spring XML Configuration

    Let's create a spring configuration file to declare and define beans for service and aspect classes

    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop="http://www.springframework.org/schema/aop"
     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-3.1.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
    
     <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
     <context:annotation-config />
     <context:component-scan base-package="com.mycompany.myapp.aspect" />
    
     <bean id="myAspect" class="com.mycompany.myapp.aspect.MyAspect">
      <!-- configure properties of aspect here as normal -->
     </bean>
    
     <bean id="myService" class="com.mycompany.myapp.service.MyService">
     </bean>
    </beans>
    Test Code
    
      Following output will be printed on console.
    do logging
    my service is called
    do sysout
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.mycompany.myapp.service.MyService;
    
    public class AspectTest {
    
     public static void main(String[] args) {
      ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
      MyService service = (MyService) applicationContext.getBean("myService");
      service.doService();
     }
    }