Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Spring Core, Spring Web and Spring Data

No description
by

Alvaro Amor

on 13 February 2014

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Spring Core, Spring Web and Spring Data

Spring Core, Spring Web, Spring Data and more Spring...
Intro
Quick Start
Beans lifecycle
Simplifying Configuration
Annotation-Based Dependency Injection

Spring Web
Spring Web MVC
Spring MVC essentials
Layouts and Views
Data binding
Spring Portlets MVC

Spring Data Access
Spring JDBC
Spring Transaction Management
Spring ORM
Spring Hibernate
Spring Data
Spring JPA
Anemic Domain Model vs. Rich Domain Model
Spring Security
Basic
Web
Spring Remoting
Spring Test
Spring AOP

Changes in 4.0


Other Spring Projects (only to show more things from Spring):
Spring Boot (similar to Spring Roo)
Spring XD
Spring Batch
Spring Integration
Spring Data: MongoDB, Neo4J, Redis, Hadoop, Gemfire, REST
Spring HATEOAS
Spring Social
Spring LDAP
Spring JMS/AMQP
Spring Web Services
Spring Web Flow
Infrastructure support for enterprise Java applications
Application Configuration
Assembly
Integration
Testing
Decoupling
Support
Accessing Data
Manage Resources
API Helpers
Data Access Technologies
Web Application Support
Struts
JSF
Spring MVC
Enterprise Support
Web Services
Messaging
Security
Scheduling
Dependency Injection / Inversion of Control
Modules
Core container
Data Access Integration
Web
AOP
Tests
Convention over Configuration
Maven:

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.7.RELEASE</version>
<scope>runtime</scope>
</dependency>
</dependencies>
Logging:

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.0.RELEASE</version>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
<scope>runtime</scope>
</dependency>
</dependencies>
Spring IoC Container (example 1)
Spring manages the lifecycle
Beans are always created in the right order
Each bean is bound to a unique id
Dependency Injection (example 2)
Constructor-based (c-namespace)
- mandatory dependencies
- promote immutability
Setter-based (p-namespace)
- allow optional dependencies and defaults
- descriptive names
- inheritance
Recommendations:
- follow design guidelines
- some classes are designed for a particular injection strategy
- be consistent
Other configurations:
lazy-init
autowiring (no, byName, byType, constructor)
bean scopes (singleton, prototype, request, session, global session, thread)
method injection (singleton/proptotype)

Lifecycle
- Initialization
Prepares for use
Application services
(are created, configured and may allocate system resources)
Application is not usable until this phase is complete

- Use
Used by clients
Application services
(process client requests, carry out application behaviors)
99.99% of the time is spent in this phase
Proxy power
A BeanPostProcessor may wrap your beans in a dynamic
proxy and add behavior to your application logic transparently

- Destruction
Shut down
Application services
(release any system resources, are eligible for garbage collector)

Load bean definitions
The XML files are parsed
Bean definitions are loaded into the context's BeanFactory (each indexed under its id)
Special BeanFactoryPostProcessor beans are invoked (can modify the definition of any bean)
This is an extension point
Useful for applying transformations to groups of bean definitions (before any objects are created)
Several implementations are provided by the framework
You can also write your own (implement the BeanFactoryPostProcessor interface)
PropertyPlaceHolderConfigurer (substitutes ${variables} in the bean definitions with values from .properties files)
<context:property-placeholder location="path"/>
Initialize bean instances
Each bean is eagerly instantiated by default (created in the right order with its dependencies injected)
After dependency injection each bean goes through a post-processing phase (where configuration and initialization can ocurr)
After post processing the bean is fully initialized and ready for use (tracked by its id until the context is destroyed)
Bean initialization steps
Bean instantiated
Dependencies injected
Bean Post Processed
Initialize the bean if instructed
A bean can optionally register for one or more initialization callbacks (useful for executing custom initialization behaviors)
There is more than one way to do it (this is the execution order if each way has its own initialization callback method)
JSR-250 --> @PostConstruct
Flexible, avoids depending on Spring APIs
Requires Spring 2.5 or later
To enable it
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<context:annotation-config/> (RequiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor)
<bean /> init-method attribute
Class with no Spring dependency
Method must be public with no arguments
Implement Spring's InitializingBean interface
Requires implementing a Spring-specific interface
public interface InitializingBean {
public void afterPropertiesSet();
}
Call special BeanPostProcessors to perform additional configuration
BeanPostProcessor
This is an extension point
Can modify bean instances
Several implementations are provided by the framework
Not common to write your own
RequiredAnnotationBeanPostProcessor
Enforces that @Required properties are set
Must be explicity enabled via configuration
To enable it
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<context:annotation-config/> (RequiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor)
Can create proxies
Bean ready for use

context.close()
Destroy bean instances if instructed
A bean can register for one or more destruction callbacks (releasing resources and cleaning up
There is more than one way to do it
(this is the execution order if each way has its own initialization callback method)
JSR-250 --> @PreDestroy
Flexible, avoids depending on Spring APIs
Requires Spring 2.5 or later
To enable it
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<context:annotation-config/>
(RequiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor)
<bean/> destroy-method attribute
Class with no Spring dependency
Method must be public with no arguments
Implement Spring's DisposableBean interface
Requires implementing a Spring-specific interface
public interface DisposableBean {
public void destroy();
}
Destroy itself (the context is not usable again)

More XML configuration options:
Bean Definition Inheritance (abstract="true" and parent)
Inner Beans (without id)
Property Editors (default and custom)
Import (file:, classpath:, classpath*:, http:, wildcards)
Bean Naming (id vs. name)
p-namespace (xmlns:p="http://www.springframework.org/schema/p")
c-namespace (xmlns:c="http://www.springframework.org/schema/c")
util-namespace
Custom Namespace
Annotation-based Configuration

It is performed before XML injection (so it can be overriden)
<context:annotation-config/>
@Required
@Autowired [required] / @Inject (JSR 330)
/ @Resource (JSR 250) / @Value
@Qualifier + Custom Qualifier / @Named (JSR 330)
@PostConstruct / @PreDestroy

<context:component-scan base-package="com.vilt"/>
<context:include-filter/> / <context:exclude-filter/>
@Component / @Controller / @Service / @Repository
/ @Named (JSR 330) / Custom
@Scope

Java-Based Configuration: @Configuration / @Bean / @Scope
Spring Web MVC
Built on the Java Servlet API
Comparable to Struts
Uses Spring for its configuration
A lot of View Technologies
Data Binding
Validation Support
i18n Support
Tag Library

Spring JavaScript
Decorate form input fields
Client-side validation
Ajax events
Fragment Rendering
AJAX
Uses DOJO


Spring Web Flow
Stateful flows
Flow Definition Language
Flows Isolation

Spring Faces
JSF UI component model with Web Flow navigation
Component library with Spring Javascript

Spring for Servlets
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

HttpServlet init
public void init() {
ApplicationContext context = WebApplicationContextUtils.
getRequiredWebApplicationContext(getServletContext));
// retrieve bean with context.getBean("beanName");
}

Request Flow

Income Request
Dispatcher Servlet (Front Controller Pattern)
HandlerMapping
Interceptor (preHandle())
HandlerAdapter
Controller (consume services)
Interceptor (postHandle())
Dispatcher Servlet
View Resolver
View
Interceptor (afterCompletion())
Dispatcher Servlet
Return Response
Context Hierarchy
Controllers

@Controller
@Autowired (to inject dependencies)
@RequestMapping (to map URL to methods)
value
method
params
Method arguments
Model
HttpServletRequest, HttpServletResponse, HttpSession, Locale, Principal
@PathVariable (URI Templates) /app/clients/3
@RequestMapping(value="/{id}")
public void show(@PathVariable("id:[\\d]*") String id) { ... }
@RequestParam (value, required) /app/clients/show?id=3
@RequestMapping
public void show(@RequestParam(value="id") String id) { ... }
Returns a Model to be used in the View, returns the View name or return the ResponseBody
View Resolver

The ViewResolver decouples the controller from the view implementation
Display Views (JSP, Tiles, Fremarker, Velocity)
File-generating Views (POI, IText, JasperReports, etc...)
Data-delivery Views (JSON, Java-XML Marshalling, Atom, RSS)

Some view resolvers:
InternalResourceViewResolver
<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>
UrlBasedViewResolver
VelocityViewResolver / FreemarkerViewResolver(different viewClass property)
ContentNegotiationViewResolver (based on media types)

Configuration:

- DispatcherServlet Context file = ${servlet-name}+"-config.xml"

- mvc-namespace
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd

- <MVC> tags
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>

Convention over Configuration:
- model.addAttribute(client); // added as "client"
- model.addAttribute(clients); // added as "clientList"
- Controller Mapped by Convention

Infrastructure Beans
- org/springframework/web/servlet/DispatcherServlet.properties
- URL Mappings
- DefaultAnnotationHandlerMapping
- ControllerClassNameHandlerMapping (method names)
- SimpleUrlHandlerMapping (declarative configuration - mappings property)
- Handler Interceptors (add common attributes, response headers,
audit, messure performance)
- preHandle(request, response, handler)
- postHandle(request, response, handler, modelAndView)
- afterCompletion(request, response, handler, exception)
- <mvc:interceptors>
- Handler Adapters
- Allows different controllers (also custom)
- @Controller, FlowExecutor, BlazeDS MessageBroker
- AnnotationMethodHandlerAdapter (@RequestMapping)
- <mvc:annotation-driven/>
- Handler Exception Resolver
- SimpleMappingExceptionResolver (or customized extension)
- @ExceptionHandler (method)
- Message Resolution
- id="messageSource" class="org.springf..ResourceBundleMessageSource"
Composite View Pattern
- Template
- Placeholders
- Re-use templates

Tiles (templating framework)
- TilesViewResolver
- org.springframework.web.servlet.view.tiles.TilesConfigurer or
org.springframework.web.servlet.view.tiles2.TilesConfigurer or
org.springframework.web.servlet.view.tiles3.TilesConfigurer
- Tiles templates (a standard JSP file with the tiles taglib)
- Tiles definitions (an XML with the definition of elements to be
included in the template
- Tiles attributes
- Placeholders
- Values: strings, templates (starts with /) o other definition
- <tiles:insertAttribute>
- <tiles:importAttribute>
Views and ViewResolvers
- URL-based views
- Content Generating Views
- BeanNameViewResolver
- ViewResolver Chain (first wins)
- Implements Ordered
- Some view resolvers return null when they can't find the View
- Others always forward
- Options for Content Type Negotiation
- Separate Methods
- Adding logic to the controller
- ContentNegotiatingViewResolver
- Detects requested content type
- Delegates to other view resolvers
- Based on: extensions, request parameters or Accepts header
- Java Activation Framework (activation.jar)
- Views associated to content types
- ignoreAcceptHeader for web applications
Spring Form tags
- <%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form" %>
- <form:form>
- modelAttribute
- method
- HiddenHttpMethodFilter
- <form:input>
- <form:select><form:option>
- Other form input types
- <form:errors>
Type Conversion
- Formatter<T> extends Printer<T>, Parser<T>
- Formatter Registration via Conversion Service

Data Binding
- Uses EL expressions (nesting, maps, strings)
- @InitBinder
- BindingResult

Validation (JSR-303 + Hibernate Validator)
- @NotNull, @Size, @Pattern, @NotEmpty
- @Valid (method)

Form Object Management
- Create it on every request
- Retrieve it on every request
- Store it in session
Portlets
- Phases (@ActionMapping / @RenderMapping / @EventMapping / @ResourceMapping)
- Modes (view, edit, help)
- web.xml
<servlet>
<servlet-name>ViewRendererServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ViewRendererServlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
- portlet.xml
<portlet>
<portlet-name>sample</portlet-name>
<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>
<portlet-info>
<title>Sample Portlet</title>
</portlet-info>
</portlet>
- Spring configuration on /WEB-INF/[portlet-name]-portlet.xml
- Different predefined controllers and handler mappings
- Interceptors
Annotation configuration

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

<bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

<bean class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

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

</beans>

- @ModelAttribute
- @SessionAttribute
What Spring can do for you?
Acquires the connection
Participates in the transaction
Executes the statement
Processes the result set
Handles exceptions
Releases the connection

Spring Resource Management
Declarative transaction management
Automatic connection management
Intelligent exception handling

Transactions
Programmatic
Declarative
@Transactional
<tx:annotation-driven transaction-manager="txManager"/>
DataSourceTransactionManager, JTATransactionManager, HibernateTransactionManager, JpaTransactionManager
Support
- JDBC
- MyBatis
- Hibernate
- JPA
- JDO

For each technology:
- A factory for the configuration
- A base support class for DAOs
- A helper as a data access template
SimpleJdbcTemplate template = new SimpleJdbcTemplate(datasource);

Constructor-based injection

SimpleJdbcDaoSupport (base class that generates the SimpleJdbcTemplate

.queryForInt .queryForLong .queryForString .queryForMap .queryForList

RowMapper, RowCallbackHandler or ResultSetExtractor

DataAccessException
DataAccessResourceFailureException
CleanupFailureDataAccessException
InvalidDataAccessApiUsageException
InvalidDataAccessResourceUsageException
DataRetrievalFailureException
OptimisticLockingFailureException
DeadlockLoserDataAccessException
DataIntegrityViolationException
UncategorizedDataAccessException
@Transactional
- Transaction starts before entering the method
- Commit at the end of the method
- Rollback if method throws a RuntimeException

Isolation
- READ_UNCOMMITED
- READ_COMMITED
- REPEATABLE_READ
- SERIALIZABLE

Propagation: REQUIRED, REQUIRES_NEW, NESTED

Read-only transactions
Hibernate:
- Session, SessionFactory and Mappings

- Annotations

- Querying (HQL)

HibernateTemplate template = new HibernateTemplate(sessionFactory);

HibernateDAOSupport

LocalSessionFactoryBean
Removes deprecated packages and methods
Includes Java 8 support
Java EE 6 and 7
Groovy Bean Definition DSL
Core Container Improvements
- Generic types as qualifier
- Bean ordering in List and Arrays
- Improvements in the Java-based configuration
- @Condicional (similar to @Profile)
- CGLIB-based proxies don't need an empty constructor
Web Improvements
- @RestController
- AsyncRestTemplate
- Time zone support
WebSocket, SockJS and STOMP messaging
Testing Improvements
Concepts: principal, authentication, authorization, secured item

Authentication mechanisms: basic, digest, form, X.509

Authorization depends on authentication and the decision process is based on roles

Motivations: portability, flexibility, extensibility, separation of concerns and consistency
Easy to use new data access technologies:
- JPA (improved)
- MongoDB (object-document)
- Neo4J (object-graph)
- Redis (key-value)
- Hadoop (big data, map-reduce)
- GemFire (elastic)
- REST
- Solr
- Couchbase
- ElasticSearch
- Cassandra
Full transcript