Thursday, December 15, 2011

Setup Spring project


Spring

The Spring Framework is a lightweight solution and a potential one-stop-shop for building your enterprise-ready applications. Spring is modular, allowing you to use only those parts that you need, without having to bring in the rest.

Spring handles the infrastructure so you can focus on your application.
Spring enables you to build applications from “plain old Java objects” (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE.

 The IoC Container

IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework's IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object. ApplicationContext is a sub-interface of BeanFactory.

The BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality. The ApplicationContext is a complete superset of the BeanFactory.

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

Configuration metadata

The Spring IoC container consumes a form of configuration metadata; this configuration metadata represents how you as an application developer tell the Spring container to instantiate, configure, and assemble the objects in your application.

Note: XML-based metadata is not the only allowed form of configuration metadata. The Spring IoC container itself is totally decoupled from the format in which this configuration metadata is actually written.

Annotation-based configuration:
Spring 2.5 introduced support for annotation-based configuration metadata.

Are annotations better than XML for configuring spring?

It depends. each approach has its pros and cons, and usually it is up to the developer to decide which strategy suits her better. Due to the way they are defined, annotations provide a lot of context in their declaration, leading to shorter and more concise configuration. However, XML excels at wiring up components without touching their source code or recompiling them. Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and, furthermore, that the configuration becomes decentralized and harder to control.

No matter the choice, Spring can accommodate both styles and even mix them together. It's worth
pointing out that through its JavaConfig option, Spring allows annotations to be used in a
non-invasive way, without touching the target components source code and that in terms of tooling,
all configuration styles are supported by the SpringSource Tool Suite (STS). Go to http://www.springsource.com/developer/sts to know more about STS.

Java-based configuration:
Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus you can define beans external to your application classes by using Java rather than XML files.

Spring configuration consists of at least one and typically more than one bean definition that the container must manage. XML-based configuration metadata shows these beans configured as <bean/> elements inside a top-level <beans/> element.

The following example shows the basic structure of XML-based configuration metadata:

<? xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
       <bean id="..." class="...">
              <!-- collaborators and configuration for this bean go here -->
       </bean>
       <bean id="..." class="...">
              <!-- collaborators and configuration for this bean go here -->
       </bean>
       <!-- more bean definitions go here -->
</beans>

id: The id attribute is a string that you use to identify the individual bean definition
class: The class attribute defines the type of the bean and uses the fully qualified class name.


The following example shows the service layer objects (services.xml) configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- services -->
       <bean id="testService" class="com.test.service.TestServiceImpl">
              <property name="testDao" ref="testDao"/>
              <!-- additional collaborators and configuration for this bean go here -->
       </bean>
       <!-- more bean definitions for services go here -->
</beans>

The following example shows the data access objects daos.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans

       <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-           method="close">
              <property name="driverClassName" value="${db.driverClassName}" />
              <property name="url" value="${db.url}" />
              <property name="username" value="${db.username}" />
              <property name="password" value="${db.password}" />
       </bean>

       <bean id="testDao" class="com.test.data.TestDAOImpl">
              <property name="dataSource" ref="dataSource"/>
              <!-- additional collaborators and configuration for this bean go here -->
       </bean>
       <!-- more bean definitions for data access objects go here -->
</beans>

The following example shows the  servlet.xml file:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd">

        <!-- the application context definition for the DispatcherServlet -->  
       <context:component-scan base-package="com.test.web" />
            
       <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
              <property name="prefix" value="/jsp/" />
              <property name="suffix" value=".jsp" />
       </bean>
              
</beans>

The following example shows the application context definition for the application project.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/tx
               http://www.springframework.org/schema/tx/spring-tx.xsd">

  <!-- the parent application context definition for the test application -->
  <bean id="propertyConfigurer"          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
        <value>classpath:jdbc.properties</value>
      </list>
    </property>
  </bean>
 
</beans>

jbdc.properties

db.driverClassName=org.apache.derby.jdbc.ClientDriver
db.url=jdbc:derby://localhost:1527/testdb
db.username=test
db.password=test


The following example shows how to configure application descriptor web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="Test" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>Test</display-name>
 
<listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
<listener>
       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
  
<context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>
              /WEB-INF/Test.xml
              /WEB-INF/test-data.xml
              /WEB-INF/Test-service.xml
              /WEB-INF/Test-servlet.xml
       </param-value>
</context-param>
      
<context-param>
       <param-name>log4jConfigLocation</param-name>
       <param-value>/WEB-INF/classes/log4j.properties</param-value>   
</context-param>
      
<servlet>
       <servlet-name>Test</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <load-on-startup>1</load-on-startup>
</servlet>
      
<servlet>
       <servlet-name>Resource Servlet</servlet-name>
       <servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class>
       <load-on-startup>1</load-on-startup>
</servlet>
      
<servlet-mapping>
       <servlet-name>Test</servlet-name>
       <url-pattern>*.do</url-pattern>
</servlet-mapping>
      
<session-config>
       <!-- minutes -->
       <session-timeout>30</session-timeout>
</session-config>

<welcome-file-list>
       <welcome-file>index.do</welcome-file>
</welcome-file-list>
      
<jsp-config>
       <taglib>
              <taglib-uri>/spring</taglib-uri>
              <taglib-location>/tld/spring-form.tld</taglib-location>
       </taglib>
</jsp-config>
</web-app>

Write your Controller


TestController.java

package com.test.web;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.test.form.TestForm;
import com.test.service.TestService;

@Controller
@RequestMapping(“/test.do”)
public class TestController {
           
@Autowired
protected TestService testService;
           
           
@RequestMapping(method=RequestMethod.GET)
public ModelAndView displayTestPage(ModelMap model, HttpSession session) {

                        if(testService!= null) System.out.println("Autowired Success!!");
                        else System.out.println("Autowired Failed!!");
                       
                        model.addAttribute("testForm", new TestForm());
                       
                        return new ModelAndView("test");
            }
           
@RequestMapping(params="submit", method=RequestMethod.POST)
public ModelAndView handleTestRequest(@ModelAttribute("testForm") TestForm testForm, BindingResult result, ModelMap model, HttpSession session, HttpServletRequest request, HttpServletResponse response) {

                        System.out.println(testForm.getName());

                        return new ModelAndView("test");
            }

}


TestForm.java

package com.test.form;

public class TestForm {
           
            private String name;

            public String getName() {
                        return name;
            }

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


@Autowired

You can use @Autowired annotation to auto wire bean on the setter method, constructor or a field.

@Controller:

The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API. However, you can still reference Servlet-specific features if you need to.

@RequestMapping


You use the @RequestMapping annotation to map URLs such as /test.do onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping for a specific HTTP method request method ("GET"/"POST") or specific HTTP request parameters.

Methods in Controller
An HTTP GET request to /test.do will be processed by displayTestPage(), which simply instantiates a new TestForm and puts it on the model. Since no attribute name is specified, by convention it will be available under the attribute name testForm.

@RequestMapping(method=RequestMethod.GET)
public ModelAndView displayTestPage(ModelMap model, HttpSession session) { }


An HTTP POST request to /test.do will be processed by handleTestRequest(), which takes the submitted TestForm, puts its one property on the model under the attribute name name and puts the TestForm itself on the model, again by convention under the attribute name testForm.

@RequestMapping(params="submit", method=RequestMethod.POST)
public ModelAndView handleTestRequest(@ModelAttribute("testForm") TestForm testForm, BindingResult result, ModelMap model, HttpSession session, HttpServletRequest request, HttpServletResponse response) { }


No comments:

Post a Comment