We have already seen Spring restful web services crud example. We have used postmon utility to demonstrate all HTTP methods such as get, post, delete and put but if you want to write java code for restful client , you can use Spring RestTemplate.

You can always use java 's HttpClient but Spring RestTemplate provides more methods and options that you can use to consume Spring restful web services via Http methods.

Here is list of methods provided by Spring Resttemplate for each http methods.

Method
Spring RestTemplate's method
Get
 getForObject, getForEntity
Post
postForObject(String url, Object request, Class responseType, String…​ uriVariables)
postForLocation(String url, Object request, String…​ urlVariables), 
Put
put(String url, Object request, String…​urlVariables)
Delete
delete()
Head
headForHeaders(String url, String…​ urlVariables)
Options
optionsForAllow(String url, String…​ urlVariables)
I am using same example which we have seen in Spring rest crud example. I am using java client instead of postman to consure Rest APIs.

Get example:

You can use getForObject or getForEntity for calling http get method.

Spring Rest API Code get method:

 @RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
 public Country getCountryById(@PathVariable int id) {
  return countryService.getCountry(id);
 }

Spring RestTemplate get Method :

package org.arpit.java2blog.client;

import org.arpit.java2blog.bean.Country;
import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

  RestTemplate restTemplate = new RestTemplate();
  Country bhutan = restTemplate
    .getForObject("http://localhost:8080/SpringRestfulWebServicesCRUDExample/country/{id}", Country.class,2);
  System.out.println("Country Name:"+bhutan.getCountryName());
  System.out.println("Population:"+bhutan.getPopulation());  
 }
}
When you run above code, you will get below output:
Country Name:Bhutan
Population:7000

Post example :

You can use PostForObject or PostForLocation to call post method.

Spring Rest API Code post method:

 @RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
 public Country addCountry(@RequestBody Country country) {
  return countryService.addCountry(country);
 }

Spring RestTemplate post Method :

package org.arpit.java2blog.client;

import org.arpit.java2blog.bean.Country;
import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

  RestTemplate restTemplate = new RestTemplate();

     final String uri = "http://localhost:8080/SpringRestfulWebServicesCRUDExample/countries";
  
     Country country = new Country();
     country.setCountryName("USA");
     country.setPopulation(4000);
  
     Country addedCountry = restTemplate.postForObject( uri, country, Country.class);
     System.out.println("Country added : " +addedCountry.getCountryName());   
 }
}
When you run above code, you will get below output:
Country added : USA

Put example :

You can use put to call http put method.

Spring Rest API Code put method:

 
 @RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
 public Country updateCountry(@RequestBody Country country) {
  return countryService.updateCountry(country);
 }

Spring RestTemplate put Method :

package org.arpit.java2blog.client;

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

import org.arpit.java2blog.bean.Country;
import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

      final String uriForPut = "http://localhost:8080/SpringRestfulWebServicesCRUDExample/countries";
        
      Country country = new Country();
      country.setId(2);
      country.setCountryName("Bhutan");
      country.setPopulation(10000);
    
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.put ( uriForPut, country);  
 }
}
When you run above code, population for bhutan will be updated to 10000.

Delete example :

You can use delete to call http delete method.

Spring Rest API Code delete method:

 
  @RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
 public void deleteCountry(@PathVariable("id") int id) {
  countryService.deleteCountry(id);

 } 

Spring RestTemplate delete Method :

package org.arpit.java2blog.client;

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

import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

   final String uriForDelete = "http://localhost:8080/SpringRestfulWebServicesCRUDExample/country/{id}";
      
      Map<String, String> params = new HashMap<String, String>();
      params.put("id","2");
    
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.delete ( uriForDelete,params);  
 }
}
When you run above code, bhutan will be deleted from list of countries.

When you want to deploy your application to tomcat server , you may do it using admin UI but how can you access it? Do you know default admin password?
Actually tomcat does not provide any default password. You need to add users to $TomcatHome/conf/tomcat-users.xml and provide role as manager-gui(For tomcat 7 and 8) and manager (For tomcat 6).

Default tomcat-users.xml

<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
</tomcat-users>
As you can see, there are no users defined in above xml.You can simply add user as below:

tomcat-users.xml

<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->

<role rolename="manager-gui"/>
<user username="arpit" password="arpit" roles="manager-gui"/>
</tomcat-users>
You need to use role as manager-gui for tomcat 7, tomcat 8 and manager for tomcat 6

In this post, we will see how to send HTTP Get/Post in java.
There are many times when you need to send http get or post request. You can use HttpURLConnection for sending get/post request in java. It belongs to java.net package.

HttpURLConnection example:

We are going to send get or post request to URLs used in restful web services CRUD example, so instead of using PostMan , we will send request using java.

Get Url:

http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
It will give you list of country in json format.

Post URL:

http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Post data:{"id":5,"countryName":"USA","population":8000}
It will create a new country resource and add it to list of counties.
Java code:
package org.arpit.java2blog.corejava;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @author Arpit Mandliya
 */
public class HttpURLConnectionExample {

 private final String USER_AGENT = "Mozilla/5.0";

 public static void main(String[] args) throws Exception {

  HttpURLConnectionExample http = new HttpURLConnectionExample();

     // Sending get request
  http.sendingGetRequest();
  
    // Sending post request
  http.sendingPostRequest();

 }

 // HTTP GET request
 private void sendingGetRequest() throws Exception {

  String urlString = "http://localhost:8080/JAXRSJsonCRUDExample/rest/countries";
  
  URL url = new URL(urlString);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();

  // By default it is GET request
  con.setRequestMethod("GET");

  //add request header
  con.setRequestProperty("User-Agent", USER_AGENT);

  int responseCode = con.getResponseCode();
  System.out.println("Sending get request : "+ url);
  System.out.println("Response code : "+ responseCode);

  // Reading response from input Stream
  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();

  while ((output = in.readLine()) != null) {
   response.append(output);
  }
  in.close();

  //printing result from response
  System.out.println(response.toString());

 }
 
 // HTTP Post request
 private void sendingPostRequest() throws Exception {

  String url = "http://localhost:8080/JAXRSJsonCRUDExample/rest/countries";
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  con.setRequestProperty("Content-Type","application/json");

  String postJsonData = "{\"id\":5,\"countryName\":\"USA\",\"population\":8000}";
  
  // Send post request
  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(postJsonData);
  wr.flush();
  wr.close();

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post Data : " + postJsonData);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();

  while ((output = in.readLine()) != null) {
   response.append(output);
  }
  in.close();
  
  //printing result from response
  System.out.println(response.toString());
 }
}
When you run above program, you will get below output:
Sending get request : http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Response code : 200
[{"id":1,"countryName":"India","population":10000},{"id":2,"countryName":"Bhutan","population":7000},{"id":3,"countryName":"Nepal","population":8000},{"id":4,"countryName":"China","population":20000}]

Sending 'POST' request to URL : http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Post Data : {"id":5,"countryName":"USA","population":8000}
Response Code : 200
{"id":5,"countryName":"USA","population":8000}
If you comment http.sendingPostRequest(); and send only get request. You will get below output:
[{"id":1,"countryName":"India","population":10000},{"id":2,"countryName":"Bhutan","population":7000},{"id":3,"countryName":"Nepal","population":8000},{"id":4,"countryName":"China","population":20000},
{"id":5,"countryName":"USA","population":8000}]
You can see USA is added to country list.

When you are working on spring or spring mvc application, you may encounter below error message.
org.xml.sax.SAXParseException: The prefix "context" for element "context:component-scan" is not bound .
or
org.xml.sax.SAXParseException: The prefix "context" for element "context:annotation-config" is not bound .

This issue generally occurs when you do not include context namespace.
For example: Lets say you have below xml configuration file.
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    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.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="controller" />

</beans>
Here you might get above exception because you are missing context namespace xmlns:context here.
When you add below line in above xml.
xmlns:context="http://www.springframework.org/schema/context"
so your final xml file will look as below:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    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.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="controller" />

</beans>
I hope it will solve context is not bound error.

In this post , we will see how to load multiple spring bean configuration files. Sometimes, you have multiple spring bean configuration file , you may have different configuration file for service, different for business object.
When you are working on complex application, it is not good practice to have only single xml configuration, you can split it into multiple file for better maintenance.
There are two ways to do it.
  • Using application context constructor
  • Using import in xml bean

Using application context constructor:

You can simply create a String array with name of multiple configuration file and pass it application context constructor.
For example:
You can load multiple files using below code:
ApplicationContext context = 
     new ClassPathXmlApplicationContext(new String[] {"spring-service.xml",
              "spring-businessObjects.xml"});

Using import: 

You can do it using import tag too.
Lets say you have spring-service.xml 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" 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">

<bean id="fetchDataService"
class="org.arpit.java2blog.FetchDataService">
 </bean>
</beans>
You have another spring configuration called spring-businessObjects.xml 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" 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">
<bean id="businessObject"
class="org.arpit.java2blog.BusinessObject">
 </bean>

</beans>
You can simply import above two files in another xml file called applicationcontext.xml. You need to load applicationcontext.xml to load all bean objects.
<?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">
    <import resource="spring-service.xml" />
    <import resource="spring-businessObjects.xml " />
 </bean>

</beans>

Sometimes you need to intercept incoming request and do some preprocessing or you need to do it after completion of request. It is very much similar to filters that we use with servlet.
There are two ways to use interceptor with Spring MVC.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example

HandlerInterceptor Interface :

We can implement HandlerInterceptor interface to use interceptor. It has three methods which we need to implement.
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) : This method is executed before request is handed over to handler method.
If you notice it has boolean return type. If this method returns true, then it will go to other interceptors or to handler method. If this method returns false then this request is handled by interceptor only and we should use response object to send back to client.

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) : This method is called when handler method has completed its process but dispatcherServlet is yet process the view. This method can be use to add some model view objects that can be used in view. It can be done by adding object to modelAndView object.

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) :  This method is called after view is render and request is completely processed.

HandlerInterceptorAdapter class:

Issue with HandlerInterceptor is that you need to implement all the methods but if you extend to abstract class called HandlerInterceptorAdapter, you can implement only those method which you want and other methods will have default implementation.

Lets implement custom interceptor example using HandlerInterceptorAdapter class.

Spring MVC interceptor example:

I am using Spring MVC hello world example here with small changes to it.
Spring MVC interceptor project structure

Adding Spring MVC dependency

Add spring dependency in pom.xml. We require spring core and spring mvc dependency here.
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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.arpit.java2blog</groupId>
  <artifactId>SpringMVCHelloWorldExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCHelloWorldExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
   <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
   </dependency>

    <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  </dependencies>
  <build>
    <finalName>SpringMVCHelloWorldExample</finalName> 
    
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
            <source>${jdk.version}</source>
            <target>${jdk.version}</target>
        </configuration>
    </plugin>
    </plugins>

  </build>
   <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
   </properties>
</project>

Create Controller 

Create a package named "org.arpit.java2blog.springmvc.controller"
create a controller class named "HelloWorldController.java"
package org.arpit.java2blog.springmvc.controller;

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

@Controller
public class HelloWorldController {
 
 @RequestMapping("/helloworld")
 public ModelAndView hello() {
      return new ModelAndView("hello");
 }
}

Create interceptor 

create interceptor class called SampleInterceptor.java
package org.arpit.java2blog.springmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SampleInterceptor extends HandlerInterceptorAdapter {

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
   throws Exception {
  request.setAttribute("blogName", "java2blog");
  return true;
 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
   ModelAndView modelAndView) throws Exception {
  String blogName = (String) request.getAttribute("blogName");
  // We are adding some modelAndView objects here and will use it in view jsp.
  modelAndView.addObject("blogName",blogName);
  modelAndView.addObject("authorName", "Arpit");
 }

 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
   throws Exception {
  String blogName = (String) request.getAttribute("blogName");
  String authorName = (String) request.getAttribute("authorName");
  System.out.println("Request URL::" + request.getRequestURL().toString());
  System.out.println("Blog name : " + blogName);
  System.out.println("Author Name : " + authorName);
 }
}

Here I am setting request attribute(blogName) in preHandle method and we are getting it in postHandle method. We are also adding two objects to modelAndView which we will use in jsp.

Create view

Modify index.jsp as below
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HelloWorld</title>
</head>
<body>
<a href="helloworld.html">Click here to read hello message </a>
</body>
</html>
Create hello.jsp in /WEB-INF/ folder
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
This is written by ${authorName} on ${blogName}
</body>
</html>

Configuring spring mvc application 

 Now we need to configure two files "web.xml" and "springmvc-dispatcher-servlet.xml" We need to declare DispatcherServlet in web.xml for spring MVC. When DisplatcherServlet is initialized,spring tries to load application context from [servlet name]-servet.xml file. So in this case, it will be try to load springmvc-dispatcher-servlet.xml.
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
     <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping> 
    </web-app>
create xml file named "springmvc-dispatcher-servlet.xml" in /WEB-INF folder as below.
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  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="org.arpit.java2blog.springmvc.controller" />
 <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <beans:property name="prefix" value="/WEB-INF/"/>
  <beans:property name="suffix" value=".jsp" />   
 </beans:bean>
 <interceptors>
  <interceptor>
   <mapping path="/helloworld.html" />
   <beans:bean
    class="org.arpit.java2blog.springmvc.interceptor.SampleInterceptor"></beans:bean>
  </interceptor>
 </interceptors>
</beans:beans>
Here we have declared interceptor(SampleInterceptor) in above file which will intercept specific URL (/helloworld.html).

It 's time to do maven build.
Right click on project -> Run as -> Maven build
Provide goals as clean install (given below) and click on run


Run the application

Right click on project -> run as -> run on server
Select apache tomcat and click on finish

 You will see below screen:



When you click on above link, you will get below screen

We are done with Spring MVC interceptor example. If you are still facing any issue, please comment.
Download

click to begin

20KB .zip


In this post, we will see Spring AOP AspectJ Annotation examples.
If you are not familiar with Spring AOP terminology, you may go through Spring Aspect oriented programming(AOP) tutorial.
Following are the AspectJ annotations which we are going to use to implement Spring AOP.
@Aspect : To declare a class as Aspect.
Annotations which are used to create Advices are:
@Before : @Before annotation is used to create before advice. It executes before actual method execution (Join points)
@AfterReturning: This annotation is used to create return advice. It executes after a method execution completes without any exception.
@AfterThrowing: This annotation is used to create After throwing advice, it executes if method exits by throwing an exception.
@After : This annotation is used to create after advice, it executes after a method execution  regardless of outcome.
@Around : This annotation is used to create around advice,  It executes before and after a join point.

This may be confusing right now but once you implement an example, it will be clear.

@Before  :

lets say you have some business logic class (BusinessLogic.java) and you want to do logging before execution of getBusinessLogic method of this class.
package org.arpit.java2blog;

public class BusinessLogic {
 
 public void getBusinessLogic() {
  System.out.println("*****************");
  System.out.println("In Business Logic method");
  System.out.println("*****************");
 }
}
Now we will create aspect class
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

 @Before("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingBeforeBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingBeforeBusinessLogic() is running!");
  System.out.println("Before execution of method : " + joinPoint.getSignature().getName());
 }

}
execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..)) is pointcut expression. It denotes execution of method loggingBeforeBusinessLogic before exection of getBusinessLogic method of BusinessLogic class.
Lets do xml configuaration of above beans in spring-config.xml.
<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:aspectj-autoproxy />
 <bean id="businessLogic" class="org.arpit.java2blog.BusinessLogic">
 </bean>
 <!-- Aspect -->
 <bean id="logAspect" class="org.arpit.java2blog.LoggingAspect" />

</beans>
Create main class named SpringAOPMain to execute the application
package org.arpit.java2blog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringAOPMain {

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-config.xml");
        BusinessLogic businessLogic = (BusinessLogic) appContext.getBean("businessLogic");
        businessLogic.getBusinessLogic();      
    }
}
When you run above program, you will get below output:
Jul 21, 2016 10:01:14 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@24174be7: startup date [Thu Jul 21 22:01:14 IST 2016]; root of context hierarchy
Jul 21, 2016 10:01:14 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
loggingBeforeBusinessLogic() is running!
Before execution of method : getBusinessLogic
*****************
In Business Logic method
*****************

@After:

I am replacing @Before method in LoggingAspect.java with @After annotated method.This method will execute after execution of actual business logic, so LoggingAspect.java will look something like this.
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;

@Aspect
public class LoggingAspect {

@After("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingAfterBusinessLogic() is running!");
  System.out.println("After execution of method : " + joinPoint.getSignature().getName());
 }
}
When you run SpringAOPMain.java again, you will get below output:
Jul 21, 2016 10:24:26 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@75783d33: startup date [Thu Jul 21 22:24:26 IST 2016]; root of context hierarchy
Jul 21, 2016 10:24:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
*****************
In Business Logic method
*****************
loggingAfterBusinessLogic() is running!
After execution of method : getBusinessLogic
As you can see in above output, loggingAfterBusinessLogic executed after getBusinessLogic method

@AfterReturning:

I am replacing @After with @AfterReturning in above LoggingAspect.java.This method will execute after execution of actual business logic but only if it successfully returns.
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;

@Aspect
public class LoggingAspect {

@AfterReturning("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingAfterBusinessLogic() is running!");
  System.out.println("After execution of method : " + joinPoint.getSignature().getName());
 }
}
When you run SpringAOPMain.java again, you will get below output:
Jul 21, 2016 10:24:26 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@75783d33: startup date [Thu Jul 21 22:24:26 IST 2016]; root of context hierarchy
Jul 21, 2016 10:24:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
*****************
In Business Logic method
*****************
loggingAfterBusinessLogic() is running!
After execution of method : getBusinessLogic

@AfterThrowing: 

Lets add one more method with @AfterThrowing annotation. It will execute if any exception occurs in getBusinessLogic method.
LoggingAspect.java
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class LoggingAspect {
 
 @AfterReturning("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingAfterBusinessLogic() is running!");
  System.out.println("After execution of method : " + joinPoint.getSignature().getName());
 }
 
 @AfterThrowing("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogicException(JoinPoint joinPoint) {

  System.out.println("Exception occurred in getBusinessLogic method");
  
 }

}
Now throw RuntimeException from getBusinessLogic to test @AfterThrowing exception. BusinessLogic.java
package org.arpit.java2blog;

public class BusinessLogic {
 
 public void getBusinessLogic() {
  System.out.println("*****************");
  System.out.println("In Business Logic method");
  System.out.println("*****************");
  throw new RuntimeException();
 }
}

When you run SpringAOPMain.java , you will get below output:
Jul 21, 2016 10:34:55 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@739474: startup date [Thu Jul 21 22:34:55 IST 2016]; root of context hierarchy
Jul 21, 2016 10:34:55 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
*****************
In Business Logic method
*****************
Exception occurred in getBusinessLogic method
Exception in thread "main" java.lang.RuntimeException
 at org.arpit.java2blog.BusinessLogic.getBusinessLogic(BusinessLogic.java:9)
 at org.arpit.java2blog.BusinessLogic$$FastClassBySpringCGLIB$$3d288cb4.invoke(<generated>)
 at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
 at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
 at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
 at org.arpit.java2blog.BusinessLogic$$EnhancerBySpringCGLIB$$1fbd989f.getBusinessLogic(<generated>)
 at org.arpit.java2blog.SpringAOPMain.main(SpringAOPMain.java:10)

As you can see loggingAfterBusinessLogicException got executed as there is exception in business logic.

@Around:

Method with @Around will get called before and after execution of business logic.
You need to call reference of ProceedingJoinPoint and call proceed method to execute actual business logic.
package org.arpit.java2blog;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class LoggingAspect {

 @Around("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAroundBusinessLogic(ProceedingJoinPoint joinPoint) throws Throwable {
  System.out.println("Before calling actual business logic"); // Before running actual business logicic
  joinPoint.proceed(); // business logic method get executed 
  System.out.println("After calling actual business logic"); // After running actual business logic
 }
}
When you run SpringAOPMain.java , you will get below output:
Jul 21, 2016 11:04:10 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@739474: startup date [Thu Jul 21 23:04:10 IST 2016]; root of context hierarchy
Jul 21, 2016 11:04:10 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Before calling actual business logic
*****************
In Business Logic method
*****************
After calling actual business logic

In this post, we will see how to create custom exception in java. It is very simple to create custom exception in java. You just need to extends Exception class to create custom exception.
Lets understand this with example. You have list of counties and if You have "USA" in list of country, then you need to throw invalidCountryException(Our custom exception).
Example: 
Create InvalidCountryException.java as below
package org.arpit.java2blog;

public class InvalidCountryException extends Exception{

 InvalidCountryException(String message)
 {
  super(message);
 }
}
Create POJO class called Country.java
package org.arpit.java2blog;

public class Country {
 
 private String name;
 
 Country(String name ){
 this.name = name;
 }
  public String toString() {
   return name;
  }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
  
 
}

Lets create CountryCheckMain.java. This class will have main method.
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;

public class CountryCheckMain {

 public static void main(String args[]) {
  List<Country> countries = new ArrayList<Country>();
  Country indiaCountry = new Country("India");
  Country chinaCountry = new Country("China");
  Country nepalCountry = new Country("Nepal");
  Country bhutanCountry = new Country("Bhutan");
  countries.add(indiaCountry);
  countries.add(chinaCountry);
  countries.add(nepalCountry);
  countries.add(bhutanCountry);
  boolean safe;
  try {
   safe = checkListOfCountries(countries);
   if (safe)
    System.out.println("We don't have USA in list of Countries");
   Country USACountry = new Country("USA");
   countries.add(USACountry);
   checkListOfCountries(countries);
  } catch (InvalidCountryException e) {
   e.printStackTrace();
  }

 }

 public static boolean checkListOfCountries(List<Country> countries) throws InvalidCountryException {
  for (int i = 0; i < countries.size(); i++) {
   Country country = countries.get(i);
   if (country.getName().equals("USA")) {
    throw new InvalidCountryException("USA is not allowed");
   }  
  }
  return true;
 }
}

When you run above program, you will get following output:
We don't have USA in list of Country
org.arpit.java2blog.InvalidCountryException: USA is not allowed
 at org.arpit.java2blog.CountryCheckMain.checkListOfCountries(CountryCheckMain.java:37)
 at org.arpit.java2blog.CountryCheckMain.main(CountryCheckMain.java:25)

As you can see, if we have "USA" in list of Countries,we are throwing InvalidCountryException.

In this post, we will see Spring interview interview questions.If you are java/j2ee developer and have some experienced on Spring, you are going to face Spring interview questions.

Here I am sharing list of important Spring interview questions.

1. What is Spring framework?

Spring framework is an open source framework created to solve the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use. Main module for Spring are Spring core,Spring AOP and Spring MVC.

2. What are main features of Spring frameworks?

  • The basic concept of the Dependency Injection or Inversion of Control is that, programmer do not need to create the objects, instead just describe how it should be created.
  • Spring contains and manages the life cycle and configuration of application objects.
  • Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. 
  • Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. 
  • The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

3. Explain main modules of Spring ?

  • Spring AOP:
    One of the key components of Spring is the AOP framework. AOP is used in Spring:
    • To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring's transaction abstraction.
    • To allow users to implement custom aspects, complementing their use of OOP with AOP
  • Spring ORM:
    The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.  
  • Spring Web:
    The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.
  • Spring DAO:
    The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
  • Spring Context:
    This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
  • Spring Web MVC:
    This is the Module which provides the MVC implementations for the web applications.
  • Spring Core:
    The Core package is the most import component of the Spring Framework.
    This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.
Spring framework Architecture
Spring Framework Architecture

4. What is dependency injection(IOC) in Spring?

The basic concept of the dependency injection (also known as Inversion of Control pattern) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

5. What are ways to inject dependency in Spring?

There are two ways to do dependency injection in Spring.

6. What is Bean in Spring?

A normal POJO class managed by Spring IOC containter are called Spring beans. It is core part of Spring application.
Example:
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
      <property name="countryName" value="India"/>
      <property name="capital" ref="CapitalBean"/>
  </bean>

7. How can you configure Spring in your application?

There are 3 ways to do it.
  • XML based configuration
  • Java based configuration
  • Annotation based configuration.

8. What is Spring XML based configuration?

In Spring XML based configuration, you define all dependency in a XML file. You define all your beans with </bean> tag in XML file and all dependencies are read using these XML file.
for example :
Sample ApplicationContext.xml file
<?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">

  <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
      <property name="countryName" value="India"/>
      <property name="capital" ref="CapitalBean"/>
  </bean>
  <bean id="CapitalBean" class="org.arpit.javapostsforlearning.Capital">
      <property name="capitalName" value="Delhi"/>
  </bean>
</beans>
You can read this ApplicationContext.xml using:
 ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

9. What is Spring java based configuration?

In Spring java based configuration, you inject all dependencies using java class only. You can use @Configuaration and @Bean annotations to do it.
package org.arpit.java2blog.config;
import org.arpit.java2blog.model.Country;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfiguration {

 @Bean(name="countryObj")
 public Country getCountry()
 {
  return new Country("India");
 }
 
}

Above file is equivalent to below spring configuration 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-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<context:annotation-config/>  
 <bean id="countryObj" class="org.arpit.java2blog.Country" >
  <property name="countryName" value="India"/>
 </bean>
</beans>
To get above bean to application context, you need to use below code
ApplicationContext appContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
 Country countryObj = (Country) appContext.getBean("countryObj");
You can refer Spring java based configuration for complete example.

10. What is spring annotation based configuration? 

You can do dependency injection via annotation also instead of XML configuration. You can define bean autowiring using annotations. You can use @Component,@Repository,@Service and @Controller annotation to configure bean in Spring application.
Annotations wiring is not turned on by default. You need to turn it on using :
<?xml version="1.0" encoding="UTF-8"?>
<bean> 
<context:annotation-config/>  
</beans>
Once you put above code, you can start using annotation on class , fields or methods.

11. What are different bean scopes in Spring?

There are 5 types of bean scopes supported in spring
  • singleton – Scopes a single bean definition to a single object instance per Spring IoC container.
  • prototype – Return a new bean instance each time when requested
  • request – Return a single bean instance per HTTP request.
  • session – Return a single bean instance per HTTP session.
  • globalSession – Return a single bean instance per global HTTP session. 

12. What is default scope of bean in Spring?

singleton is default scope of a bean in Spring. You have to explicitly change scope of a bean if you want different scope.

13. What is ApplicationContext and what are its functions?

ApplicationContext is an central interface for providing configuration information to an application.
An ApplicationContext provides the following functionalities:
  • Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
  • The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
  • The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
  • The ability to publish events. Implementations must provide a means of registering event listeners.
  • Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

14. How do you injection collection in Spring?

You can initialize collection using list and value tag as below:
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <property name="listOfStates">
   <list>
    <value>Maharastra</value>
    <value>Madhya Pradesh</value>
    <value>Rajasthan</value>
   </list>

  </property>
 </bean>

15. What do you mean by bean autowiring in Spring?

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in <bean>.The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration
<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" autowire="byName">

16. What are different modes of autowiring supported by Spring?

There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection.
no:
Default, no auto wiring, set it manually via “ref” attribute as we have done in dependency injection via settor method post.
byName:
Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file and it tries to match it with name of bean in xml configuration file.
byType:
Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
contructor:
byType mode in constructor argument.
autodetect:
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

17. What is Spring AOP?

Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.

18. What is Aspect, Advice, Join point and pointcut in Spring AOP?

Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name. 
Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.
Advice : Action taken by  aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.
Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.

19. What is @Qualifier annotation in Spring?

You can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.
You can read about Spring @Qualifier annotation for more details.

20. What is @Required annotation in Spring? 

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.
Suppose you have very large application and you get NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.
You can read about Spring @Required annotation for more details.

You may also like:
    core java interview questions web services interview questions restful web services interview questions Data structure and algorithm Interview Questions Hibernate interview questions Java Collections interview questions Java String interview questions

This is 16 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
We have already seen Spring core tutorial before. In this tutorial, we will see concept about Spring AOP and how to implement it.

Spring AOP:

Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.

Why AOP?

It provides pluggable way to apply concern before, after or around business logic.
Lets understand with the help of logging. You have put logging in different classes but for some reasons, if you want to remove logging now, you have to make changes in all classes but you can easily solve this by using aspect. If you want to remove logging, you just need to unplug that aspect.

AOP concepts:

Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name. 
Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.
Advice : Action taken by  aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.
Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.
Target object : These are the objects on which advices are applied. For example: There are the object on which you want to apply logging on joint point.
AOP proxy : Spring will create JDK dynamic proxy to create proxy class around target object with advice invocations.
Weaving : The process of creating proxy objects from target object may be termed as weaving.

Types of Advices :

Advice is action taken by aspect at particular joint point.
Before Advice: it executes before a join point.
After Returning Advice: it executes after a joint point completes without any exception.
After Throwing Advice: it executes if method exits by throwing an exception.
After Advice: it executes after a join point regardless of outcome.
Around Advice: It executes before and after a join point.

You can see implementation of Spring AOP AspectJ example here.

In this post, we will see interview questions on java String. String is most important data type which we use in our programs very often.

1. Why String is declared final or immutable in java?

There are various reasons to make String immutable.
  • String pool
  • Thread Safe
  • Security
  • Class Loading
  • Cache hash value
You can refer why String is immutable in java for more details.

2. How to reverse a String in java? Can you write a program without using any java inbuilt methods?

Anagrams means if two String have same characters but in different order. For example: Angel and Angel are anagrams There are many ways to do it, some of them are:
  • Using for loop
  • Using recursion
  • Using StringBuffer
Please refer to the solution at reverse a String in java

3. How to check if two Strings are anagram in java?

There are many ways to check if Strings are anagrams. Some of them are:
  1. Using String methods
  2. Using array.sort
Please refer to solution at check if two Strings are anagram in java

4. How to check if String has all unique characters in java?

There are multiple ways to find if String has all unique characters or not.
  • By using HashSet
  • Using indexOf and lastIndexOf methods of String
  • By Using ascii value of characters.
Please refer to complete solution at check if String has all unique characters.

5. How to check if one String is rotation of another String in java?

Lets say you need to check whether str1 and str2 is rotation of one another or not.
  1. Create a new String with str3= str1 + str1
  2. Check if str3 contains str2 or not.
  3. if str3 contains str2 then str2 is rotation of str1 else it is not
You can find complete solution at check if one String is rotation of another in java.

6. Write a java program to find duplicate characters in String in java?

  1. Create a HashMap and character of String will be inserted as key and its count as value.
  2. If Hashamap already contains char,increase its count by 1, else put char in HashMap.
  3. If value of Char is more than 1, that means it is duplicate character in that String.

7. Find first non repeated character in String in java?

There are may ways to find it.
Some of them are:
  • Using LinkedHashMap
  • Using indexOf and lastIndexOf methods.
Please find complete solution at find first non repeated character in  a String.

8. Find all substrings of String in java?

Java program to find all substrings of a String.
For example: If input is "abb"  then output should be "a", "b","b", "ab", "bb", "abb"
We will use String class's subString method to find all subString.
Please refer to complete solution at find all subStrings of String.

9. Find length of String without using any inbuilt method in java?

You can use try catch block for catching StringIndexOutOfBoundException and when this exception aries, you can simply return i(Index at which you will get the exception)
Please refer to complete solution at find length of String without inbuilt methods.

10. Write a java program to print all permutations of String in java?

Take out first character of String and insert into different places of permutations of remaining String recursively. Please find complete solution at how to find all permutations of String in java.

11. What is the difference between creating String as new() and literal?

If you create a String using new operator, it is not interned. It will  create new object in heap memory even if String object already exists with same content.
        String str1=new String("Java2Blog");
        String str2=new String("Java2Blog");
        System.out.println(str1==str2);
It will return false as str1 and str2 will point to different object
If you create a String using assignment operator, it goes to the String constant pool and it is interned. If you create another String with same content, both will reference to same object in String constant pool.
String str1="Java2Blog";
String str2="Java2Blog";
System.out.println(str1==str2);
It will return true as str1 and str2 will point to same object in String constant pool.

12. How many objects will be created in below code?

String str1= "java2blog";
String str2= "java2blog";
Only one object will be created and will be stored in String constant pool.

13. How do you convert String to char array in java?

You can use string's toCharArray() method to convert String to char array.

14. What is difference between StringBuffer and StringBuilder in java?

Parameter
StringBuffer
StringBuilder
Thread-safe
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously.
StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously. 
Performance
It is less performance efficient as it is thread-safe
It is more performance efficient as it is not thread-safe.

15. How many objects will be created in below code?

String str1= new String("java2blog");
String str2= new String("java2blog");
Three objects will be created here, two in heap memory and one in String constant pool.
You may also like:
    core java interview questions web services interview questions restful web services interview questions Data structure and algorithm Interview Questions Spring interview questions Hibernate interview questions Java Collections interview questions

In this post, we will see how to find all permutations of String in java.
We will use a very simple approach to do it.
Take out first character of String and insert into different places of permutations of remaining String recursively.
Lets say you have String as ABC.
So we take out A from ABC
First character =A and RemainingString = BC 
As we are applying recursion here, we will find permutations of BC.
Take out B from BC.
First character= B and RemainingString = C 
As we are applying recursion here, we will find permutations of C.
When we take out C, our String size becomes 0 and that is our base case here.
First character = C and RemainingString = "" 
We insert C to differences indexes of Permutations  of RemainingString(""), so we get permutation of C as C.
We insert B to different indexes of Permutations of remainingString(C), so we get BC and CB.
C: BC, CB
Now we insert A to different indexes in BC and CB.
BC : ABC , BAC , BCA
CB : ACB, CAB, CBA
so thats how we got all permutations of ABC.
It may look tricky but once you practice the solution, you will be able to understand it better.

Java program to find all Permutations of String in java:

package org.arpit.java2blog;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class PermutationOfStringJava {

 public static void main(String[] args) {

     Set<String> set=permutationOfString("ABC");
     System.out.println("Permutations of String ABC are:");
     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
   String string = (String) iterator.next();
   System.out.println(string);   
  }
 }
 
 public static Set<String> permutationOfString(String str)
 {
  Set<String> permutationSet=new HashSet<String>();
  
  if(str.length()==0)
  {
   permutationSet.add("");
            return permutationSet;
  }
   
  // take out first character of String
  char c=str.charAt(0);
  // Remaining String
  String rem=str.substring(1);
  
  
  Set<String> permutatedSetForRemainingString=permutationOfString(rem);
  for (String permutedString: permutatedSetForRemainingString) {
   for (int j = 0; j <= permutedString.length(); j++) {
    String permutation=insertFirstCharAtDiffPlaces(permutedString,c,j);
    permutationSet.add(permutation);
   }
    
  }
  return permutationSet;
  
 }
 public static String insertFirstCharAtDiffPlaces(String perm,char firstChar,int index)
 {
  // Inserting firstCharacter of orig String at difference places based on index
  return perm.substring(0,index)+firstChar+perm.substring(index);
 }

}
When you run above program, you will get following out:
Permutations of String ABC are:
ACB
ABC
BCA
CBA
CAB
BAC
 

Java tutorial for beginners Copyright © 2012