Spring

Configure an H2 in memory Database in Spring Boot.

Posted on

Spring Boot has great build in support for H2 database so here we will see how to configured in-memory database H2 using Spring Boot.

H2 is an open source embedded database built on java ships in a single .jar file. Therefore you can easily embed an h2 database into your application. H2 Database has a built in the web based console that you can use to interact with the database. You can use H2 database as an in-memory database, embedded database or network database. You can file more details from here.

It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.

First of all here are the maven dependencies for spring boot to use H2 Database. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>com.spring.boot.example</groupId>
    <artifactId>Spring_H2_Example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring_boot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.194</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Here, we created a SQL Schema file and dummy file under resource folder ( main/java/resources ), When our application gets started then it creates table and inserts into it.

sql/schema.sql file

DROP TABLE IF EXISTS User_Details;
create table User_Details (id integer not null auto_increment,
 email varchar(255),
 first_Name varchar(255),
 last_Name varchar(255),
 password varchar(255), primary key (id)
);

sql/data.sql file

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('admin@admin.com','admin','admin','admin');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('rahul@gmail.com','Rahul','sharma','rahul@ku123123!');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('shyam_babul@yahoo.com','Sham','babul','shyam#babul!2123');

Since Spring boot can auto configure in-memory database ( h2 ) so you don’t need to provide configuration details unless the application has been configured in other ways. If you see in below application.properties file where it has been configured from where Schema and SQL file should be picked up from resources folder.

application.properties file contains all the required configurations to connect h2 database and run Spring Boot.

# Spring Boot can auto-configured H2 database.

spring.jpa.database=H2
spring.datasource.url=jdbc:h2:mem:test;MODE=Oracle
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.max-active=1
spring.jpa.hibernate.ddl-auto=false
spring.h2.console.enabled=true
spring.h2.console.settings.trace=true
spring.h2.console.settings.web-allow-others=true
spring.h2.console.path=/h2
spring.datasource.schema=classpath*:sql/schema.sql
spring.datasource.data=classpath*:sql/data.sql


# Here, We create a new "local" Datasource for our application using it we can perform 'ddl' and 'dml' operations.
# Hence, it's redundant but we enabled spring data source.

local.datasource.url=jdbc:h2:mem:test;MODE=Oracle
local.datasource.username=sa
local.datasource.password=
local.datasource.driver-class-name=org.h2.Driver
local.datasource.max-active=1

Model Class

package com.spring.boot.example.domain;

public class UserDetails {

    private long id;
    private String email;
    private String first_name;
    private String last_name;
    private String password;

    public long getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

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

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("UserDetails{");
        sb.append("id=").append(id);
        sb.append(", email='").append(email).append('\'');
        sb.append(", first_name='").append(first_name).append('\'');
        sb.append(", last_name='").append(last_name).append('\'');
        sb.append(", password='").append(password).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

Repository Class


package com.spring.boot.example.repo;

import com.spring.boot.example.domain.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDetailsRepository {

@Autowired
private JdbcTemplate jdbcTemplate;

public List printUserDetailsData(){
return jdbcTemplate.query("SELECT * FROM USER_DETAILS",new UserDetailsRowMapper());
}

class UserDetailsRowMapper implements RowMapper{

@Override
public UserDetails mapRow(ResultSet resultSet, int i) throws SQLException {
UserDetails userDetails = new UserDetails();
userDetails.setId(resultSet.getInt("id"));
userDetails.setEmail(resultSet.getString("email"));
userDetails.setFirst_name(resultSet.getString("first_Name"));
userDetails.setLast_name(resultSet.getString("last_Name"));
userDetails.setPassword(resultSet.getString("password"));
return userDetails;
}
}
}

Main Class

package com.spring.boot.example;

import com.spring.boot.example.domain.UserDetails;
import com.spring.boot.example.repo.UserDetailsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

@SpringBootApplication(exclude = JmsAutoConfiguration.class)
public class H2MainApp {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =  SpringApplication.run(H2MainApp.class, args);
        List<UserDetails> userDetailsList = context.getBean(UserDetailsRepository.class).printUserDetailsData();
        for(UserDetails userDetails : userDetailsList){
            System.out.println(userDetails);
        }
    }

    @Bean
    @ConfigurationProperties(prefix = "local.datasource")
    public DataSource getDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

Output:-

2017-08-12 15:11:57.899 INFO 4956 — [ main] com.spring.boot.example.H2MainApp : Started H2MainApp in 7.839 seconds (JVM running for 8.638)
UserDetails{id=1, email=’admin@admin.com’, first_name=’admin’, last_name=’admin’, password=’admin’}
UserDetails{id=2, email=’rahul@gmail.com’, first_name=’Rahul’, last_name=’sharma’, password=’rahul@ku123123!’}
UserDetails{id=3, email=’shyam_babul@yahoo.com’, first_name=’Sham’, last_name=’babul’, password=’shyam#babul!2123′}

Also, H2 Web Console can be enabled by enabling these properties in application.properties. It is a convenient way to view the tables created and run queries against the in memory database.  Here is an example of the H2 database console.

Keep these properties in your application.properties to enable H2 Web Console.

spring.h2.console.enabled=true

spring.h2.console.settings.web-allow-others=true

spring.h2.console.path=/h2

 

Advertisements

How to load Profile Specific Properties files in Spring Boot

Posted on

In this articles, we will see how to load Profile specific properties files from resource directory in Spring Boot application.

Here, we set up a sample Spring Boot Project and maintains set of configuration files specific to the Profile which would be loaded when the Application runs.

Total four configuration files are created in this sample Project:-

application.properties – Which is a parent property that always loaded first before Profile specific properties file.

application.${spring.profiles.active}.properties – This is a Profile specific properties file where ${spring.profiles.active} is a placeholder of any Env i.e DEV/UAT/PROD. This property file will be loaded right after parent properties. We can keep all Profile related configuration here additionally we can overwrite derived properties of parent property file.

spring.profiles.active – Spring provides this property to enabled active Profile which you have to provide in VM argument with Environment name.

-Dspring.profiles.active=dev

 

 

 

 

Here, we see Project setup hierarchy and configuration files created under resource folder ( /src/main/resources ).

 

 

 

 

 

 

 

 

 

application.properties file is parent properties file that contains all common properties which will be derived by Profile specifies properties file.

file.upload.size.limit =  1024
remote.connection.url=localhost
remote.connection.port=8080
remote.connection.username=user123
remote.connection.password=Pa$$wOrd


remote.https.enabled = false
remote.connection.auth=false

application-dev.properties  ( When application runs on DEV Profile then load all derived properties of application.properties file as well as it own properties )

env.name=dev

application-uat.properties ( When application runs on UAT Profile then Load and Overwrite properties value if it exists in parent properties file  )

file.upload.size.limit =  102400
remote.connection.url=220.120.56.80
remote.connection.port=9090
remote.connection.username=uatUser
remote.connection.password=UAT$123#

remote.https.enabled = true

env.name=UAT

application-prod.properties

file.upload.size.limit =  102400
remote.connection.url=220.110.56.63
remote.connection.port=9090
remote.connection.username=prodAdmin
remote.connection.password=Pa$$wOrd@233$

remote.https.enabled = true
env.name=PROD
remote.connection.auth=true

PropertiesUtils.Java:- This Utilities Class load all properties file in specified order means first it loads application.properties then load Profile specifies properties ( application.${spring.profiles.active}.properties ).

/**
 * Created by MYPC on 8/4/2017.
 */

package com.spring.example.utils;

        import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
        import org.springframework.core.io.ClassPathResource;
        import org.springframework.core.io.Resource;

        public class PropertiesUtils {

            public static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";

            public static void initProperties() {
                String activeProfile = System.getProperty(SPRING_PROFILES_ACTIVE);
                if (activeProfile == null) {
                    activeProfile = "dev";
                }
                PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
                        = new PropertySourcesPlaceholderConfigurer();
                Resource[] resources = new ClassPathResource[]
                        {new ClassPathResource("application.properties"),
                                new ClassPathResource("application-" + activeProfile + ".properties")};
                propertySourcesPlaceholderConfigurer.setLocations(resources);

            }
        }

Finally, Main class which read all properties file and print on the Console.


package com.spring.example;

import com.spring.example.utils.PropertiesUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * list
 * Created by AJAY KUMAR on 1/9/2017.
 */
@SpringBootApplication
public class MainApplication {

    @Value("${file.upload.size.limit}")
    private long size;

    @Value("${remote.connection.url}")
    private String remoteConnectionUrl;

    @Value("${remote.connection.port}")
    private int remoteConnectionPort;

    @Value("${remote.connection.username}")
    private String remoteConnectionUsername;

    @Value("${remote.connection.password}")
    private String remoteConnectionPassword;

    @Value("${remote.https.enabled}")
    private String remoteHttpsEnabled;

    @Value("${env.name}")
    private String envName;

    @Value("${remote.connection.auth}")
    private String remoteConnectionAuth;

    public static void main(String[] args) {
        PropertiesUtils.initProperties();
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
        MainApplication mainApplication = context.getBean(MainApplication.class);
        printEnvironmentsProperties(mainApplication);
    }

    private static void printEnvironmentsProperties(MainApplication MainApplication) {
        StringBuilder stringBuilder = new StringBuilder("Properties Files ......\n");

        stringBuilder.append("env.name").append(" : ").append(MainApplication.envName).append("\n")
                .append("file.upload.size.limit").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.url").append(" : ").append(MainApplication.remoteConnectionUrl).append("\n")
                .append("remote.connection.port").append(" : ").append(MainApplication.remoteConnectionPort).append("\n")
                .append("remote.connection.username").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.password").append(" : ").append(MainApplication.remoteConnectionPassword).append("\n")
                .append("remote.connection.auth").append(" : ").append(MainApplication.remoteConnectionAuth).append("\n")
                .append("remote.https.enabled").append(" : ").append(MainApplication.remoteHttpsEnabled).append("\n");
        System.out.println(stringBuilder.toString());
    }
}

By default, spring-profiles-active is dev Profile either you set active profile to dev or not, it loads application-dev.properties and give below output-

2017-08-05 17:37:35.068 INFO 11548 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.457 seconds (JVM running for 5.036)
Properties Files ……
env.name : dev
file.upload.size.limit : 1024
remote.connection.url : localhost
remote.connection.port : 8080
remote.connection.username : 1024
remote.connection.password : Pa$$wOrd
remote.connection.auth : false
remote.https.enabled : false

When you set spring-profiles-active is PROD  in VM options then you will get below output.

2017-08-05 17:41:06.539 INFO 10184 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.095 seconds (JVM running for 4.783)
Properties Files ……
env.name : PROD
file.upload.size.limit : 102400
remote.connection.url : 220.110.56.63
remote.connection.port : 9090
remote.connection.username : 102400
remote.connection.password : Pa$$wOrd@233$
remote.connection.auth : true
remote.https.enabled : true

I hope this article would be helpful!! Thanks.

Developing a RESTful Web Service Using Spring Boot 1.4

Posted on

spring_mvc_rest

 

 

 

In this article, we will see the full example of developing an application using Spring boot 1.4.3 Release version. Along with MVC RESTFul example to accomplish a CURD operation.

Before we kick off in example details, we would give you some insight about Spring.boot

What is Spring Boot ?

It is a framework for developing a stand-alone application, Its provide defaults for code and annotation configuration that help us to quickly start new Spring project.

Spring Boot is nothing but a top up on existing Spring Framework with embedded Server ( Jetty + Tomcat ). The goal of Spring Boot Framework is to minimize the development and Testing ( JUnit & Integration ) time and provide production ready features like a metrics, health, logs and externalized configuration.

Features

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated ‘starter’ POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration.

Advantages of Spring Boot:

  • It is very easy to develop Spring Based applications with Java or Groovy.
  • It reduces lots of development time and increases productivity.
  • It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  • It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
  • It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
  • It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  • It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy) Applications from command prompt very easily and quickly.
  • It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle
  • It provides lots of plugins to work with embedded and in-memory Databases very easily.

Let start with Spring Boot Example Step by Step :-

It’s is recommended to start spring.boot application using dependency management system like Maven or Gradle. Here we use Maven to build a Spring Boot application. Below are dependencies in pom.xml which can be created manually or created by SPRING INITIALIZR – recommended to use it to develop a simple Spring Boot Application.

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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>com.spring.boot.example</groupId>
    <artifactId>Spring_Boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <!--http://start.spring.io/-->
    <name>spring_boot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Create a RESTFul Controller that handle CURD operation using endpoints. Spring 4.3 introduced new annotations which serve the same purpose as @RequestMapping having predefined ‘method’ (HTTP verb) value. These annotations are actually themselves annotated with @RequestMapping with the related value of ‘method’ element.

Followings are those annotations:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

DevOpsController.java

package com.spring.example.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * Created by MYPC on 1/9/2017.
 */
@RestController
public class DevOpsController {

    @GetMapping
    public ResponseEntity<?> sayHello() {
        return ResponseEntity.status(HttpStatus.OK).body("Welcome to my first Sprint boot example");
    }

    @PutMapping
    public ResponseEntity<?> putMethod(@RequestBody String payload) {
        System.out.println(" Put Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @PostMapping
    public ResponseEntity<?> postMethod(@RequestBody String payload) {
        System.out.println(" POST Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @DeleteMapping
    public ResponseEntity<?> deleteMethod(@RequestBody String payload) {
        System.out.println(" DELETE Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @GetMapping(path = "/list")
    public ResponseEntity<?> getList() {
        List list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Four");
        return ResponseEntity.status(HttpStatus.OK).body(list);
    }
}

And Main Application class to start Spring-Boot application along with Server.


package com.spring.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * list
 * Created by AJAY KUMAR on 1/9/2017.
 */
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.spring.example.controller")
public class SpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args);
    }
}


 

Run SpringBootApplication.java as normal java program, It will start embedded Tomcat on port no 8080. Below are output’s snapshot.
springboot-rest

Inversion of control and Dependency Injection Patterns

Posted on Updated on

Inversion of control  and Dependency Injection : –

Inversion of control is a generic principle, while Dependency injection realises this principle as design pattern for object graph construction (i.e. configuration controls how the objects are referencing each other, rather than the object itself controlling how to get the reference to another object).

Inversion of Control  implies change the flow of control in the program. In traditional standalone application we have Main method that control the flow to third party libraries ( if third party libraries exist) but through inversion of controls, control gets transferred from third party library code to our code as we are taking the service of third party library

 

Don’t call us, we’ll call you”.

Let have an example here:-  

When you are using a desktop computer, you are slaved (or say, controlled). You have to sit before a screen and look at it. Using keyboard to type and using mouse to navigate. And a bad written software can slave you even more. If you replaced your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of computer controlling it.

Some Key Points about IOC :- 

  • It’s about getting freedom ( no dependencies at all )
  • Loose coupling – decouple
  • high cohensive
  • easy to test and mock the real object as well
  • reuseabilty

The Dependency Inversion Principle (DIP) states that higher level classes and lower level class does’t interact directly but instead it’s working on some abstraction modules where both classes get the flexibility of increasing the functionalities.

– High level modules should not depend upon low level modules. Both should depend upon abstractions.
– Abstractions should not depend upon details. Details should depend upon abstractions.

 

Injecting a prototype/Session bean into a singleton bean

Posted on Updated on

spring-logo

 

 

 

In Spring, most of the beans we work with are Singletons. If a singleton bean is wired with yet another singleton bean, there is absolutely no problem. But if it is wired with a bean which is of different scope, say prototype, how does it work? Here is the example:
RequestProcessor.Java


public class RequestProcessor {

    private RequestValidator validator;

    public void handleRequest(String requestId){
        validator.validate(requestId);
        // Process the request and update
    }

    public RequestValidator getValidator() {
        return validator;
    }

    public void setValidator(RequestValidator validator) {
        this.validator= validator;
    }

}

RequestValidator.Java


public class RequestValidator {

    private List errorMessages = new ArrayList();

    public RequestValidator() {
        System.out.println("Validator instance created!");
    }

    // Validates the request and populates error messages
    public void validate(String requestId){

    }

    public List getErrorMessages() {
        return errorMessages;
    }

}

And here is the spring configuration:


<bean id="requestProcessor" class="com.pramati.spring.RequestProcessor">
<property name="validator" ref="validator"/>
</bean>

<bean id="validator" scope="prototype" class="com.pramati.spring.RequestValidator"/>

With this configuration, it is expected that when ever I fetch requestProcessor from application context, it will be wired with a new validator as we declared the validator bean is of prototype scope. But this does not happen.
When the application context gets initialized, it sees that requestProcessor is a singleton bean and initializes it to the context after wiring it with all the dependencies set. So from then onwards when we request context for requestProcessor, it return the same bean every time. To solve this issue, we have 2 approaches:

1.Lookup Method injection: For this, we have to declare the beans as follows:


<bean id="requestProcessor" class="com.pramati.spring.RequestProcessor">
 <lookup-method name="getValidator" bean="validator"/>
</bean>

<bean id="validator" scope="prototype" class="com.pramati.spring.RequestValidator"/>

The Spring Framework implements method injection by using CGLIB library to generate dynamically a subclass that overrides the method. So for the method to be overridden, we have to define that method in the class and either provide a dummy implementation for it or make it abstract. Making a method abstract implies that class also has to be made abstract which will make it difficult to unit test. So providing a dummy implementation is a better choice.
Whenever we define a bean with lookup methods, Spring creates a subclass of the bean and overrides those methods which are marked as lookup-methods. And this subclassed bean gets registered into the context. The subclass delegates all the non-lookup methods to the original class. For the lookup methods, it overrides the implementation. So in our example, when getValidator() is called, it returns a new validator instance.
We can roughly imagine our new subclass(registered in container) like this:


requestProcessor = new RequestProcessor(){
    public RequestValidator getValidator(){
        return context.getBean("validator");
    }
};

We could have directly fetched the bean from application context in RequestProcessor itself. But this would mean that the class is directly coupled to Spring framework. To do this in a cleaner way, we can use lookup injection. This puts all the spring related stuff at one place.

2. Scoped Proxies: This can be implemented as:


<bean id="requestProcessor" class="com.pramati.spring.RequestProcessor">
<property name="validator" ref="validator"/>
</bean>

<bean id="validator" scope="prototype" class="com.pramati.spring.RequestValidator">
<!-- This instructs the container to proxy the current bean-->
<aop:scoped-proxy/>
</bean>

Remember, in the case of look up method injection, proxy is created for singleton bean. But in case of scoped proxies, proxy is created for prototype bean and wired into the singleton bean during the process of registering the singleton bean in the context. The proxy thus created understands the scope and returns instances based on the requirements of the scope. So in our case, requestProcessor holds a reference to proxy in place of validator.
And in case of lookup method injection, when requestProcessor gets loaded into the context, validator will not be initialized at all. And when we call the look up method, it returns the prototype bean. But instead of calling the method, if you try to directly access the prototype bean(assuming it is accessible), it gives a Nullpointer Exception as it didn’t get initialized(We are not wiring it using property tag of bean)
In case of this, we can also configure how a proxy can be created. It can be done in 2 ways:-

  1. CGLIB library which directly subclasses the object. This is the default option of Spring. For this, we must have CGLIB library our class path.
  2. Java Dynamic Proxies. For this to be activated, we have to call:

<aop:scoped-proxy proxy-target-class="false"/>

Here in this case, we don’t need any additional libraries in our class path. But the scoped bean must implement at least one interface and it has to be referred through the same interface at all places in order to get itself wired.

Few points to note:
1. Both method injection and scoped proxies work not only for prototype beans. This works more generic. Whenever a bean of different scope is injected into a singleton bean, we can use any of these techniques to ensure that we get a corresponding scope object.
2. Note that in the proxy, the method returning the prototype bean is overridden to return a new instance for every single call.
Suppose we want to display the error messages that we have got after validation:


requestProcessor.getValidator().validate();
for(String message: requestProcessor.getValidator().getErrorMessages()){
logger.log(LogLevel.ERROR, message);
}

This code seems to print the error messages we have got after validation process. But this will never print any error messages even if there are many validation failures. This happens because requestProcessor.getValidator() returns a new validator instance every time it is called. So for this to work, the code has to be modified as:


RequestValidator validator = requestProcessor.getValidator();
validator.validate();
for(String message: validator.getErrorMessages()){
logger.log(LogLevel.ERROR, message);
}

This happens only in case of prototype beans but works perfectly in case of other non-singleton scopes(request, session, global-session).

The singleton scope
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

The session scope
With the above bean definition in place, the Spring container will create a brand new instance of the bean , for the lifetime of a single HTTP Session.
According to Spring framework reference, a different approach needs to be followed in cases where a class which “lives longer”(singleton bean in this case) needs to be injected with another class having a comparatively shorter life-span(session-scoped bean). The approach is different for prototype & singleton scope though.
In your XML, what we want is that the singletonBean instance should be instantiated only once, and it should be injected with sessionBean. But since sessionBean is session-scoped(which means it should be re-instantiated for every session), the configuration is ambiguous(as the dependencies are set at instantiation time and the session scoped value can change later also).
So instead of injecting with that class, it’s injected with a proxy that exposes the exact same public interface as sessionBean. The container injects this proxy object into the singletonBean bean, which is unaware that this sessionBean reference is a proxy. It’s specified by writing this tag in the sessionBean:


<aop:scoped-proxy/>

XML Configuration:


<bean name="singletonBean" class="somepkg.SingletonBean">
<property name="someProperty" ref="sessionBean"/>
</bean>

<bean name="sessionBean" class="somepkg.SessionBean" scope="session">
<aop:scoped-proxy/>
</bean>

When a singletonBean instance invokes a method on the dependency-injected sessionBean object, it actually is invoking a method on the proxy. The proxy then fetches the real sessionBean object from (in this case) the HTTP Session, and delegates the method invocation onto the retrieved real sessionBean object.

Singleton beans with prototype-bean dependencies

Lookup Method Injection

When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.
However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.


<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean>

<!-- commandProcessor uses statefulCommandHelper -->
<bean id="commandManager" class="fiona.apple.CommandManager">
<lookup-method name="createCommand" bean="command"/>
</bean>

Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. The lookup typically involves a prototype bean as in the scenario described in the preceding section. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method.

This Topic is copied from this site.

Spring4 + Hibernate 4 + JSON Example with XML Configuration

Posted on Updated on

spring_mvc_rest

 

 

 

 

 

In this article, we will show you how to produce JSON as a Http response.

Technologies used:

  1. JDK 1.6
  2. Spring 4.0.3.RELEASE
  3. Hibernate 4.3.4.Final
  4. Jackson 2.4.1
  5. Eclipse 3.6
  6. Maven 3

Project hierarchy in Eclipse :-

Spring4HibernateJSONExample-project-hierarchy

 

 

 

 

 

 

 

 

 

 

 

 

Following REST Services to be Exposed:-

REST service URI Methods Parameter Description
/API/enquiry GET None Fetch out all record of enquiry
/API/enquiry/{enquiry_id} GET enquiry_id Fetch out a specified record of enquiry Table base on {enquiry_id}
/API/enquiry POST Send Enquiry Object in JSON format Add a record
/API/enquiry/{enquiry_id} DELETE enquiry_id Delete a specified record from Enquiry Table.
/API/enquiry PUT Send Enquiry Object in JSON format Update existing record

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

<groupId>com.spring.itexpert</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>Spring4HibernateJSONExample</artifactId>
<name>Spring4HibernateJSONExample</name>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<description>
Root Project For Spring + Hibernate + JSON Application
</description>
<properties>

<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<cglib.version>2.2.2</cglib.version>
<!-- Spring -->
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<hibernate.version>4.3.4.Final</hibernate.version>

<jackson-version>2.4.1</jackson-version>
</properties>

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

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring JDBC Support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring core & mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- CGLib for @Configuration -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Servlet API Support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
</dependencies>

<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/web</warSourceDirectory>
<warName>Spring4HibernateJSONExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>

<finalName>Spring4HibernateJSONExample</finalName>
</build>
</project>

Spring-servlet.xml:-


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:annotation-config />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:component-scan base-package="com.spring.itexpert" />

</beans>

web.xml


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<display-name>Web Application</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

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

hibernate.cfg.xml


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<mapping class="com.spring.itexpert.hibernate.model.Enquiry" />
</session-factory>
</hibernate-configuration>

jdbc.properties:-


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/myDB
jdbc.username=root
jdbc.password=root

EnquiryController.Java  :


package com.spring.itexpert.controller;

import java.security.Principal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.spring.itexpert.dao.EnquiryRepository;
import com.spring.itexpert.hibernate.model.Enquiry;


@Controller
@RequestMapping("/API/enquiry")
public class EnquiryController {

	@Autowired
	private EnquiryRepository enquiryRepository;
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(method=RequestMethod.GET)
	public List getListOfEnquiry(){
		List enquiries = enquiryRepository.getListOfEnquriry();
		return enquiries;
	}
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(value="/{enquiry_id}",method=RequestMethod.GET)
	public Enquiry getEnquiry(@PathVariable("enquiry_id") Long enquiry_id){
		System.out.println(enquiry_id);
		return enquiryRepository.getEnquiry(enquiry_id) ;
	}
	
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(method=RequestMethod.POST)
	public void getSaveEnquiry(Principal principal, @RequestBody Enquiry e){
		enquiryRepository.save(e);;
	}
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(value="/{enquiry_id}",method=RequestMethod.DELETE)
	public  void deleteEnquiry(@PathVariable("enquiry_id") Long enquiry_id, Principal principal){
		enquiryRepository.delete(enquiry_id);
	}
	
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(method=RequestMethod.PUT)
	public void editEnquiry(@RequestBody Enquiry e,Principal principal){
		System.out.println(e);
		enquiryRepository.update(e);
	}
		
}


EnquiryRepository.Java


package com.spring.itexpert.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.spring.itexpert.hibernate.model.Enquiry;


@Repository
@Transactional
public class EnquiryRepository {

	@Autowired
	private SessionFactory sessionFactory;

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public List getListOfEnquriry() {
		List list = getSession().createCriteria(Enquiry.class).list();
		return list;
	}
	public List getListOfEnquriry(Integer maxPageSize,Integer maxRecord) {
		List list = getSession().createCriteria(Enquiry.class)
				.setMaxResults(maxRecord)
				.setFirstResult(maxPageSize)
				.list();
		return list;
	}
	
	public void update(Enquiry e){
		getSession().merge(e);
	}
	
	public void save(Enquiry e){
		getSession().merge(e);
	}
	
	public void delete(Long enquiry_id){
		Enquiry e = (Enquiry)getSession().get(Enquiry.class, enquiry_id);
		getSession().delete(e);
		
	}
	
	public Enquiry getEnquiry(long id){
		Enquiry e = (Enquiry)getSession().get(Enquiry.class, id);
		System.out.println(e.toString());
		return e != null? e:new Enquiry();
	}
	
}


Enquiry.Java


package com.spring.itexpert.hibernate.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "enquiry")
public class Enquiry {

	@Id
	@GeneratedValue
	private long id;
	private String name;
	private String course;
	private String status;
	private String preferences;
	private String location;
	private String place;
	private String remarks;
	private String email;

	private String source;
	private String mobile;
	@Column
	@Temporal(TemporalType.TIMESTAMP)
	@Type(type="timestamp")
	private Date enquiry_date;
	
	@Column
	@Temporal(TemporalType.TIMESTAMP)
	@Type(type="timestamp")
	private Date updated_date;
	
	
	public Enquiry(){}
	
	public Enquiry(String studentname, String course, String status,
			String preference, String remarks, String email, String source,
			String mobile,Date enquiry_date) {
		this.name = studentname;
		this.course = course;
		this.status = status;
		this.preferences = preference;
		this.remarks = remarks;
		this.email = email;
		this.source = source;
		this.mobile = mobile;
		this.enquiry_date = enquiry_date;
	}

	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setStudentname(String studentname) {
		this.name = studentname;
	}
	public String getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public String getPreferences() {
		return preferences;
	}
	public void setPreference(String preference) {
		this.preferences = preference;
	}
	public String getRemarks() {
		return remarks;
	}
	public void setRemarks(String remarks) {
		this.remarks = remarks;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getSource() {
		return source;
	}
	public void setSource(String source) {
		this.source = source;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	

	public Date getEnquiry_date() {
		return enquiry_date;
	}

	public void setEnquiry_date(Date enquiry_date) {
		this.enquiry_date = enquiry_date;
	}

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

	public void setPreferences(String preferences) {
		this.preferences = preferences;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getPlace() {
		return place;
	}

	public void setPlace(String place) {
		this.place = place;
	}

	public Date getUpdated_date() {
		return updated_date;
	}

	public void setUpdated_date(Date updated_date) {
		this.updated_date = updated_date;
	}

	@Override
	public String toString() {
		return String
				.format("Enquiry [id=%s, name=%s, course=%s, status=%s, preferences=%s, location=%s, place=%s, remarks=%s, email=%s, source=%s, mobile=%s, enquiry_date=%s, updated_date=%s]",
						id, name, course, status, preferences, location, place,
						remarks, email, source, mobile, enquiry_date,
						updated_date);
	}

	
}


Spring MVC + JSON = 406 Not Acceptable + characteristics not acceptable according to the request “accept” headers ()

Posted on Updated on

This is the  very common mistake that typically happened during the configuration Spring + JSON. Recently we faced such issues with Spring 4 + Hibernate configuration so by digging some blogs and own effort make this issues fixed.

below are some steps that need to be changed in configuration file so we can get rid of “Response Error 406 :-characteristics not acceptable according to the request “accept” headers ()

Get rid of this issues by adding **@EnableWebMvc** in Controller class.

@Controller
@RequestMapping("/API/course")
@EnableWebMvc
public class CourseController {
@Autowired
private com.item.DAO.CourseRepository courseRepository;

@ResponseStatus(value=HttpStatus.OK)
@RequestMapping(method=RequestMethod.GET)
public @ResponseBody List<Course> getListOfCourse(){
List<Course> courses = courseRepository.getListOfCourse();
return courses ;
}

or add following lines in xml configuration file if XML configuration is being used in your project.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<bean>

and add following dependencies in your pom.xml file:-


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.1</version>
</dependency>

See complate example here.

We hope this will help you out, Thanks !!