++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Spring’s declarative transaction management features make the web application fully transactional
You simply need to wire up your business logic using an ApplicationContext and use a WebApplicationContext to integrate your web layer.
---------------------------------------------------------------------------------------------------------------
In Web.xml
---------------------------------------------------------------------------------------------------------------
a) We will define the context-param in web.xml - this will be used to hold application context xml / spring config files .
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext*.xml
classpath:dataAccessContext.xml
</context-param>
b) Listeneres adn Servlet Definitions::
Dispatcher Servlet - which will direct the action calls from UI/form submission to respective actions in controllers.
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:cm-web-servlet.xml</param-value>
</init-param>
</servlet>
cm-web-servlet.xml -> holds configuration to include various spring modules/classes as per the requirement
also called as configuration metadata
i) DefaultAnnotationHandlerMapping
ii) AnnotationMethodHandlerAdapter
iii) InternalResourceViewResolver
iv) ResourceBundleViewResolver
v) ResourceBundleMessageSource
vi) CommonsMultipartResolver
xsi:schemaLocation - if we see the schema imported then we can understand the spring mappings/modules actually used.
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring- security-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
hence : Spring Beans, Spring COntext, Spring AOP, Spring Security, Spring MVC, Spring Task, Spring Util
c) Maven "Bill Of Materials" Dependency to avoid issues due to different version of Spring JARS, hence we can configure spring-framework-bom in Dep. Mgmt
d) Logging is the only mandatory external dependency and Commons-logging is by default available as a dependency resolved thrugh Spring-core
e) SLF4J is a cleaner dependency and more efficient at runtime than commons-logging because it uses compile-time bindings instead of runtime discovery of the other logging frameworks it integrates
f) Many people run their Spring applications in a container like IBM WAS - this causes problems with Logging , In such cases with WAS the easiest thing to do is to invert the class loader hierarchy (IBM calls it "parent last") so that the application controls the JCL dependency, not the container.
g) 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
The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container
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.
Types: a) Setter-based DI 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.
<bean id="exampleBean" class="examples.ExampleBean">
<!-- setter injection using the nested ref element -->
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
<!-- setter injection using the neater ref attribute -->
<property name="beanTwo" ref="yetAnotherBean"/>
<property name="integerProperty" value="1"/>
</bean>
b) Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency
In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}
}
<beans>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean>
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
</beans>
The container can use type matching with simple types if you explicitly specify the type of the constructor argument using the type attribute. For example:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
+++++++++++++++++ Constructor-based or setter-based DI +++++++++++++++++++++++
Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies.
The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null
Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In Spring, 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.
h) The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.
Configuration metadata is traditionally supplied in a simple and intuitive XML format
Other forms of metadata for Spring Containere
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. To use these new features, see the @Configuration, @Bean, @Import and @DependsOn annotations.
Spring configuration consists of at least one and typically more than one bean definition that the container must manage.
you define service layer objects, data access objects (DAOs), presentation objects such as Struts Action instances, infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so forth
i) Instantiating a Spring IoC container is straightforward. The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, and so on.
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
j) following example shows the service layer objects (services.xml) configuration file
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
i) It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer or module in your architecture
You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resource locations, as was shown in the previous section. Alternatively, use one or more occurrences of the <import/> element to load bean definitions from another file or files.
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
j) Using the container
The ApplicationContext enables you to read bean definitions and access them as follows:
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
However, we generally need not to do it manually as when we actually configure the spring application set up the config metadata (app ctxt xml)
will enable and provide all required initiations
Spring’s integration with web frameworks provides for dependency injection for various web framework classes such as controllers and JSF-managed beans
++++++++++++++++++++++++++++ Spring Web MVC framework ++++++++++++++++++++++++++
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files.
a) With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features
b) Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.
c) For Spring based validation at controller level - An @RequestBody method parameter can be annotated with @Valid, in which case it will be validated using the configured Validator instance.
d) @RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.
e) An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model.
f) As a result of data binding there may be errors such as missing required fields or type conversion errors. To check for such errors add a BindingResult argument immediately following the @ModelAttribute argument:
The spring-test module offers first class support for testing annotated controllers.
h)Interceptors located in the handler mapping must implement HandlerInterceptor from the org.springframework.web.servlet package. This interface defines three methods: preHandle(..) is called before the actual handler is executed; postHandle(..) is called after the handler is executed; and afterCompletion(..)
i) RedirectView
One way to force a redirect as the result of a controller response is for the controller to create and return an instance of Spring’s RedirectView. In this case, DispatcherServlet does not use the normal view resolution mechanism. Rather because it has been given the (redirect) view already, the DispatcherServlet simply instructs the view to do its work.
The RedirectView issues an HttpServletResponse.sendRedirect() call that returns to the client browser as an HTTP redirect. By default all model attributes are considered to be exposed as URI template variables in the redirect URL. Of the remaining attributes those that are primitive types or collections/arrays of primitive types are automatically appended as query parameters.
++++++++++++++++++++ Spring OXM +++++++++++++++++++++
Spring's Object/XML Mapping support. : - converting an XML document to and from an object. This conversion process is also known as XML Marshalling, or XML Serialization.
a marshaller is responsible for serializing an object (graph) to XML
an unmarshaller deserializes the XML to an object graph
Spring’s declarative transaction management features make the web application fully transactional
You simply need to wire up your business logic using an ApplicationContext and use a WebApplicationContext to integrate your web layer.
---------------------------------------------------------------------------------------------------------------
In Web.xml
---------------------------------------------------------------------------------------------------------------
a) We will define the context-param in web.xml - this will be used to hold application context xml / spring config files .
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext*.xml
classpath:dataAccessContext.xml
</context-param>
b) Listeneres adn Servlet Definitions::
Dispatcher Servlet - which will direct the action calls from UI/form submission to respective actions in controllers.
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:cm-web-servlet.xml</param-value>
</init-param>
</servlet>
cm-web-servlet.xml -> holds configuration to include various spring modules/classes as per the requirement
also called as configuration metadata
i) DefaultAnnotationHandlerMapping
ii) AnnotationMethodHandlerAdapter
iii) InternalResourceViewResolver
iv) ResourceBundleViewResolver
v) ResourceBundleMessageSource
vi) CommonsMultipartResolver
xsi:schemaLocation - if we see the schema imported then we can understand the spring mappings/modules actually used.
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring- security-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
hence : Spring Beans, Spring COntext, Spring AOP, Spring Security, Spring MVC, Spring Task, Spring Util
c) Maven "Bill Of Materials" Dependency to avoid issues due to different version of Spring JARS, hence we can configure spring-framework-bom in Dep. Mgmt
d) Logging is the only mandatory external dependency and Commons-logging is by default available as a dependency resolved thrugh Spring-core
e) SLF4J is a cleaner dependency and more efficient at runtime than commons-logging because it uses compile-time bindings instead of runtime discovery of the other logging frameworks it integrates
f) Many people run their Spring applications in a container like IBM WAS - this causes problems with Logging , In such cases with WAS the easiest thing to do is to invert the class loader hierarchy (IBM calls it "parent last") so that the application controls the JCL dependency, not the container.
g) 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
The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container
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.
Types: a) Setter-based DI 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.
<bean id="exampleBean" class="examples.ExampleBean">
<!-- setter injection using the nested ref element -->
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
<!-- setter injection using the neater ref attribute -->
<property name="beanTwo" ref="yetAnotherBean"/>
<property name="integerProperty" value="1"/>
</bean>
b) Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency
In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}
}
<beans>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean>
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
</beans>
The container can use type matching with simple types if you explicitly specify the type of the constructor argument using the type attribute. For example:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
+++++++++++++++++ Constructor-based or setter-based DI +++++++++++++++++++++++
Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies.
The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null
Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In Spring, 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.
h) The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.
Configuration metadata is traditionally supplied in a simple and intuitive XML format
Other forms of metadata for Spring Containere
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. To use these new features, see the @Configuration, @Bean, @Import and @DependsOn annotations.
Spring configuration consists of at least one and typically more than one bean definition that the container must manage.
you define service layer objects, data access objects (DAOs), presentation objects such as Struts Action instances, infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so forth
i) Instantiating a Spring IoC container is straightforward. The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, and so on.
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
j) following example shows the service layer objects (services.xml) configuration file
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
i) It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer or module in your architecture
You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resource locations, as was shown in the previous section. Alternatively, use one or more occurrences of the <import/> element to load bean definitions from another file or files.
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
j) Using the container
The ApplicationContext enables you to read bean definitions and access them as follows:
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
However, we generally need not to do it manually as when we actually configure the spring application set up the config metadata (app ctxt xml)
will enable and provide all required initiations
Spring’s integration with web frameworks provides for dependency injection for various web framework classes such as controllers and JSF-managed beans
++++++++++++++++++++++++++++ Spring Web MVC framework ++++++++++++++++++++++++++
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files.
a) With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features
b) Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.
c) For Spring based validation at controller level - An @RequestBody method parameter can be annotated with @Valid, in which case it will be validated using the configured Validator instance.
d) @RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.
e) An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model.
f) As a result of data binding there may be errors such as missing required fields or type conversion errors. To check for such errors add a BindingResult argument immediately following the @ModelAttribute argument:
The spring-test module offers first class support for testing annotated controllers.
h)Interceptors located in the handler mapping must implement HandlerInterceptor from the org.springframework.web.servlet package. This interface defines three methods: preHandle(..) is called before the actual handler is executed; postHandle(..) is called after the handler is executed; and afterCompletion(..)
i) RedirectView
One way to force a redirect as the result of a controller response is for the controller to create and return an instance of Spring’s RedirectView. In this case, DispatcherServlet does not use the normal view resolution mechanism. Rather because it has been given the (redirect) view already, the DispatcherServlet simply instructs the view to do its work.
The RedirectView issues an HttpServletResponse.sendRedirect() call that returns to the client browser as an HTTP redirect. By default all model attributes are considered to be exposed as URI template variables in the redirect URL. Of the remaining attributes those that are primitive types or collections/arrays of primitive types are automatically appended as query parameters.
++++++++++++++++++++ Spring OXM +++++++++++++++++++++
Spring's Object/XML Mapping support. : - converting an XML document to and from an object. This conversion process is also known as XML Marshalling, or XML Serialization.
a marshaller is responsible for serializing an object (graph) to XML
an unmarshaller deserializes the XML to an object graph
No comments:
Post a Comment