Spring

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

Difference between @Component and @Bean in Spring

Posted on Updated on

spring-logo

This is also frequently asked interview question for experience Java interview question. Most of Java developer  get confused to deliver the right answer to interviewer. Though Spring also create a lot of confusion about annotation and manual base configuration and other things but good concept and knowledge are always appreciable.

Here, In this section we will discuss difference between @component (@service,@repository and @controller) and @bean annotation.

First of all @component is a generic annotation and it can be used across the application. In enterprises or multi-layer application it is classified into @service,@repository and @controller for more code readable and understandable.

Technically on multi-layer application has application layer, Service layer,business layer and persistence layer. Subsequently annotations are used to represent it.

Different between @Component and @Bean

@Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework. Spring container automatically scan and identify all beans annotated by @Component, @Service, @Repository and @Controller.
Service Layer :-

@Service("userService")
public class UserService {

....

}

Persistence Layer :-

@Repository("userDAO")
public class UserDAO {

....

}

Controller / Presentational Layer :-

@Controller("userController")
public class UserController {

....

}

Root component Package defined in spring configuration xml file then spring container scan and initialized all classes present in the classpath coming under the base-package annotated.

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

@Bean annotation is used to explicitly declare a single bean rather than letting spring container do it automatically. It decouples the declaration of bean from bean definition.


public class AuthenticationService {
	
	private static final Logger logger = Logger.getLogger(AuthenticationService.class);
        ...
        ...
}
@Configuration
public class AppConfig {
@Bean(name="authenticationService")
    public AuthenticationService getAuthenticationService(){
    	return new AuthenticationService();
    }
}

 

More stereotype annotation details as below :- 

  • @Component – generic and can be used across application.
  • @Service – annotate classes at service layer level.
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Repository – annotate classes at persistence layer, which will act as database repository.

Disable automatic scan of @Component, @Repository, @Service, @Controller:


<beans>
<context:component-scan use-default-filters = "false" base-package="com.service" /> 
</beans>