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

Monday, 22 May 2017

What are the different types of dependency injections in spring?

Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies into the object externally, and you make it somebody else's problem. This "someone" is either an object further up the dependency graph, or a dependency injector (framework) that builds the dependency graph.

Spring supports 2 types of dependency injection
Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument.

1) Constructor- based dependency injection
It is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

2) Setter-based dependency injection
It is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Spring Setter vs. Constructor Injection
1. Partial dependency: Partial dependency can be injected using setter injection but it is not possible by the constructor. Suppose there are 4 properties in a class, having 4 arguments constructor and setters methods. In such case, if you want to pass information to only one property, it is possible by setter method only.

2. Overriding: Setter injection overrides the constructor injection. If we use constructor and setter injection, IOC container will use the setter injection.

3. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like a constructor. So setter injection is flexible than constructor injection.

4. Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml.

5. There is one drawback of setter Injection is Security. By using setter injection, we can override certain dependency which is not possible which is not possible with constructor injection because every time we call the constructor, a new object is gets created.

6. Setter and Constructor injection in Spring, where later can help if there is a circular dependency between two object A and B.

When to use Setter Injection over Constructor Injection in Spring?
Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring, we use XML files, readability is a much bigger concern. Also, the drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using "dependency-check" attribute of the tag.

Once the number of dependencies crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via the constructor. Setter Injection is preferred choice when the number of dependencies to be injected is a lot more than normal, if some of those arguments are optional than using Builder design pattern is also a good option.

Wednesday, 10 May 2017

Spring REST Web Service and Content Negotiation

com.spring.restful.controller.WebConfig.java
This customized class should be in the same package in which our controller exists because we are using <context:component-scan base-package="com.spring.restful" /> to scan the controller package.

We need to override the configureContentNegotiation method of the WebMvcConfigurerAdapter for content negotiations.
package com.spring.restful.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
importorg.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
      /** Total customization. */
      @Override
      public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
            configurer.favorPathExtension(false).
            favorParameter(true).
            parameterName("mediaType").
            ignoreAcceptHeader(true).
            useJaf(false).
            defaultContentType(MediaType.APPLICATION_JSON).
            mediaType("xml", MediaType.APPLICATION_XML).
            mediaType("json", MediaType.APPLICATION_JSON);

      }
}

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"
      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>SpringRestFulService</display-name>
      <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
            <servlet-name>rest</servlet-name>
            <servlet-class>
                  org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
            <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
            <servlet-name>rest</servlet-name>
            <url-pattern>/*</url-pattern>
      </servlet-mapping>
</web-app>

rest-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:mvc="http://www.springframework.org/schema/mvc"
      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
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

      <!-- Enables the Spring MVC @Controller programming model -->
      <annotation-driven />

      <!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->
      <beans:bean
      class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <beans:property name="messageConverters">
                  <beans:list>
                        <beans:ref bean="jsonMessageConverter" />
                  </beans:list>
            </beans:property>
      </beans:bean>

      <!-- To convert JSON to Object and vice versa -->
      <beans:bean id="jsonMessageConverter"
      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      </beans:bean>
      <context:component-scan base-package="com.spring.restful" />

</beans:beans>

com.spring.restful.controller.UserDetailsService.java
package com.spring.restful.controller;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import com.spring.restful.dao.UserDAO1;
import com.spring.restful.model.UsersDTO;

@RestController
public class UserDetailsService {

      @RequestMapping(value="/user/{msisdn}",
                  method = RequestMethod.GET,
                  produces={"application/xml", "application/json"})
      public @ResponseBody UsersDTO
                  getUserInformation( @PathVariable(value="msisdn")  String msisdn) {
           
            UsersDTO dto = UserDAO1.getUserDetail(msisdn);

            return dto;
      }

}

com.spring.restful.dao.UserDAO1.java
package com.spring.restful.dao;
import java.util.Date;
import com.spring.restful.model.UsersDTO;
public class UserDAO1 {
      public static UsersDTO getUserDetail(String msisdn) {
            /* we can fetch the user information from DB. */
            UsersDTO users = new UsersDTO();
            users.setUserId("123");
            users.setUserName("Rajesh");
            users.setDob(new Date());
            users.setMsisdn(msisdn);
            return users;
      }
}

com.spring.restful.dao.UsersDTO.java
package com.spring.restful.model;
import java.util.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class UsersDTO {

      private String userId;
      private String userName;
      private Date dob;
      private String msisdn;
     
      @XmlElement
      public String getUserId() {
            return userId;
      }
      public void setUserId(String userId) {
            this.userId = userId;
      }
     
      @XmlElement
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
     
      @XmlElement
      public String getMsisdn() {
            return msisdn;
      }
      public void setMsisdn(String msisdn) {
            this.msisdn = msisdn;
      }
     
      @XmlElement
      public Date getDob() {
            return dob;
      }
      public void setDob(Date dob) {
            this.dob = dob;
      }
}

Note:
For XML binding, we need to put annotation on the DTO class fields.
For json response, we need to put the jackson-mapper  jars in class path only.


Sample Request to fetch the data:

Jar needed:
Spring core jar
Spring web jar
commons-logging-1.1.1.jar
jackson-annotations-2.5.4.jar
jackson-core-2.2.0.jar
jackson-databind-2.1.4.jar
jaxb-api-2.2.jar for XML binding
jstl-1.2.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar.
Related Posts Plugin for WordPress, Blogger...