Sie sind auf Seite 1von 15

Spring Quick Start

Quick start to understand the basic of Spring framework development.

Spring hello world example


Maven + Spring 2.5.6 hello world example.

Spring 3.0 hello world example (Spring 3.0)


Maven + Spring 3.0 hello world example, what are needed in new Spring 3.0
development.

Spring loosely coupled example


An example to show demonstrate how Spring make components loosely coupled.

Spring Dependency Injection (DI)

How Spring to do dependency Injection (DI) to manage object dependencies.

Spring Dependency Injection (DI)


How Spring applies the Dependency Injection (DI) design pattern via
Setter Injection and Constructor Injection.

Spring DI via setter method


Dependency injection a bean via setter method.

Spring DI via constructor


Dependency injection a bean via constructor.

Constructor injection type ambiguities in Spring


The constructor injection argument type ambiguity issue is always
happening in a bean which contains multiple constructor methods with
many arguments.

Bean Basic

All the classes you need to use in Spring Ioc container are considered bean, and declared in
a Spring bean configuration file or via annotation.

Spring bean reference example


How beans access to each other by specify the bean references in the
same or different bean configuration file.

Inject value into bean properties in Spring


Three ways to inject value into bean properties.

Load multiple Spring bean configuration file


Developers always categorize different bean configuration files in different

modules folder, heres a tip to show you how to load multiple Spring bean
configuration files.

Spring inner bean examples


Whenever a bean is used for one particular property only, its always
advised to declare it as an inner bean.

Spring bean scopes examples


Bean scope is used to decide which type of bean instance should be return
from the Spring container back to the caller.

Spring Collections (List, Set, Map, and Properties) example


Example to inject values into collections type (List, Set, Map, and
Properties).

ListFactoryBean example
Create a concrete List collection class (ArrayList and LinkedList), and inject
it into bean property.

SetFactoryBean example
Create a concrete Set collection class (HashSet and TreeSet), and inject it
into bean property.

MapFactoryBean example
Create a concrete Map collection class (HashMap and TreeMap), and inject
it into bean property.

Spring inject Date into bean property CustomDateEditor


Normally, Spring is accepting date variable, heres a tip to use
CustomDateEditor to work around it.

Spring PropertyPlaceholderConfigurer example


Externalize the deployment details into a properties file, and access from a
bean configuration file via a special format ${variable}.

Spring bean configuration inheritance


Inheritance is very useful for a bean to share common values, properties
or configuration.

Spring dependency checking


Spring comes with 4 dependency checking modes to make sure the
required properties have been set in bean.

Spring dependency checking with @Required Annotation


Dependency checking in annotation mode.

Custom @Required-style annotation


Create a custom @Required-style annotation ,which is equivalent to
@Required annotation.

Bean InitializingBean and DisposableBean example


Perform certain actions upon bean initialization and destruction.
(interface)

Bean init-method and destroy-method example


Perform certain actions upon bean initialization and destruction. (XML)

Bean @PostConstruct and @PreDestroy example


Perform certain actions upon bean initialization and destruction.
(Annotation)

Spring Expression Language (Spring 3.0)

Spring 3.0 introduces features rich and powerful expression language known as Spring
expression language, or Spring EL.

Spring EL hello world example


Quick start to use the Spring expression language (EL).

Spring EL bean reference example


Reference bean, bean property using a dot (.) symbol.

Spring EL method invocation example


Call bean method in directly.

Spring EL operators example


Spring EL supports most of the standard relational, logical and
mathematical operators.

Spring EL ternary operator (if-then-else) example


Conditional check , if else then.

Spring EL Arrays, Lists, Maps example


Works with Map and List.

Spring EL regular expression example


The regular expression to evaluate the condition.

Test Spring EL with ExpressionParser


Show you how to test Spring El easily.

Spring Auto Component Scanning

Spring is able to scan, detect and register your bean automatically.

Spring Auto scanning components


Enable Spring to auto scan, detect and register your beans.

Spring Filter components in auto scanning


Example to filter certain components in auto scanning mode.

Spring AutoWiring Bean

Spring auto-wiring modes to wire or beans automatically, both in XML and annotation.

Spring Auto-Wiring Beans


Summary of 5 types auto wiring modes in Spring.

Spring Autowiring by Type


If the data type of a bean is compatible with the data type of other bean
property, auto wire it.

Spring Autowiring by Name


If the name of a bean is same as the name of another bean property, auto
wire it.

Spring Autowiring by Constructor


Actually, its autowiring by Type in constructor argument.

Spring Autowiring by AutoDetect


It means choosing autowire by constructor if default constructor is
found, otherwise uses autowire by type.

Spring Autowiring with @Autowired annotation


Examples to show how to define auto-wiring modes in annotation.

Spring Autowiring @Qualifier example


Example to identify which bean is qualified to autowired on a field.

Spring AOP (Aspect-oriented programming)

The Spring AOP modularize cross-cutting concerns in aspects. Put it simply, an interceptor to
intercept some methods.

Spring AOP Example Advice


Examples and explanations about different types of Springs advices.

Spring AOP Example Pointcut , Advisor


Examples and explanations about different types of Springs Pointcut and
Advisor.

Spring AOP interceptor sequence


The sequence of the AOP interceptor will affect the functionality.

Auto proxy creator example


An auto proxy creator example to create proxy object for your beans
automatically, useful to avoid creating many duplicated proxy objects.

Spring AOP + AspectJ framework

AspectJ supported since Spring 2.0, more flexible and powerful. However, this example is
demonstrated in Spring 3.0.

Spring AOP + AspectJ annotation example (Spring 3.0)


An example to show you how to integrate AspectJ annotation with Spring
framework.

Spring AOP + AspectJ in XML configuration example (Spring 3.0)


Spring AOP with AspectJ in XML base configuration.

Spring Object/XML Mapper (Spring 3.0)

In Spring 3.0, Object to XML mapping (OXM) is moved from the Spring Web Services to the
core Spring Framework.

Spring Object/XML mapping example


Spring oxm + castor, convert Object to XML and vice verse.

Spring JDBC Support

Spring provides many helper classes to simplify the overall JDBC database operation.

Spring + JDBC example


An example to show how to integrate Spring and JDBC.

JdbcTemplate + JdbcDaoSupport example


Example to use Springs JdbcTemplate and JdbcDaoSupport classes to
simplify the overall JDBC database operation processes.

JdbcTemplate Querying examples


Here are a few examples to show how to use JdbcTemplate query()
methods to query or extract data from database.

JdbcTemplate batchUpdate() example


A batchUpdate() example to show how to perform the batch insert
operations.

SimpleJdbcTemplate Querying examples


More user friendly and simple way to query or extract data from database.

SimpleJdbcTemplate batchUpdate() example


Another batch update example with SimpleJdbcTemplate, a java5-friendly
supplement to JdbcTemplate.

Named Parameters examples in SimpleJdbcTemplate


An example to show how to use named parameter as SQL parameter
values, and this is only supported in SimpleJdbcTemplate.

Spring Hibernate Support

Spring comes with many handy classes to support Hibernate ORM framework.

Maven + Spring + Hibernate + MySql Example


A simple project of using Spring and Hibernate.

Maven + (Spring + Hibernate) Annotation + MySql Example


A simple project of using Spring and Hibernate (annotation version).

Spring AOP transaction management in Hibernate


An example to show how to manage the Hibernate transaction with Spring
AOP.

Struts + Spring + Hibernate integration


Example to integrate Spring with Struts and Hibernate framework.

Spring E-mail Support

Springs provides MailSender to send email via JavaMail API.

Sending E-mail via MailSender


Example to use Springs MailSender to send an email via Gmail SMTP
server.

E-mail template in bean configuration file


Hard-code all the email properties and message content in the method
body is not a good practice, you should consider define the email message
template in the Springs bean configuration file.

Sending e-mail with attachment


Example to use Spring to send an email that has attachments.

Spring Scheduling Support

Spring has very good support in both JDK timer and Quartz framework.

Spring + JDK Timer scheduler example


An article about how Spring schedules a job with JDK timer.

Spring + Quartz scheduler example


An article about how Spring schedules a job with Quartz framework.

Spring + Struts + Quartz scheduler example


Integrate Spring with Struts and schedule a job with Quartz framework.

Integrating Spring with Other Web Frameworks

Spring integrates with other web frameworks.

Spring dependency injection in the servlet session listener


Spring comes with a ContextLoaderListener listener as a generic way to
enable the Spring dependency injection in session listener and almost all
other web framework.

Struts + Spring integration


Example to integrate Spring with Struts 1.x framework.

Struts 2 + Spring integration example


Example to integrate Spring with Struts 2 framework.

JSF 2.0 + Spring integration example


Example to integrate JSF 2.0 with Spring framework.

JSF 2.0 + Spring + Hibernate integration example


Example to integrate JSF 2.0 + Spring + Hibernate framework together.

Wicket + Spring integration example


Example to integrate Wicket with Spring framework.

Struts 2 + Spring + Quartz scheduler integration example


Example to integrate Spring + Struts 2 + Quartz.

Struts 2 + Spring + Hibernate integration example


Example to integrate Spring + Struts 2 + Hibernate.

Spring FAQs

Install Spring IDE in Eclipse


An article about how to install Spring IDE in Eclipse.

Resource bundle with ResourceBundleMessageSource example


ResourceBundleMessageSource is the most common class to resolve text
messages for different locales.

Access MessageSource in bean (MessageSourceAware)


An example to show how to get the MessageSource in a bean via
MessageSourceAware interface.

Resource loader with getResource() example


Springs resource loader provides a very generic getResource() method to
get the resources like (text file, media file, image file) from the file
system , classpath or URL.

Spring Common Errors

Some Spring common error messages.

ClassNotFoundException :
org.springframework.web.context.ContextLoaderListener

Cannot proxy target class because CGLIB2 is not available

CGLIB is required to process @Configuration classes

java.lang.ClassNotFoundException: org.exolab.castor.xml.XMLException

java.lang.ClassNotFoundException: org.apache.xml.serialize.XMLSerializer

1. Spring MVC Hello World

Some hello world examples to quick start Spring MVC framework.

Gradle Spring 4 MVC Hello World Example (XML Configuration)

Gradle Spring 4 MVC Hello World Example (@JavaConfig + Servlet 3)

Maven Spring 3 MVC Hello World Example (XML Configuration)

Maven Spring 3 MVC Hello World Example (@JavaConfig + Servlet 3)

Spring 3 REST Example (Working)

Spring 4 REST Example (Working)

@Deprecated Maven + Spring 2.5.6 MVC hello world example

@Deprecated Maven + Spring 2.5.6 MVC hello world annotation example

New & Updated

Spring 4 MVC Ajax Example

Spring 4 Form Handling Example

Spring 4 + Logback Example

2. Handler Mapping

Define how web request (URL) maps to the Controller handlers.

BeanNameUrlHandlerMapping example
Maps the requested URL to the name of the cocntroller.

ControllerClassNameHandlerMapping example
Uses convention to map the requested URL to Controller.

SimpleUrlHandlerMapping example
Allow developer to specify the mapping of URL patterns and handler
mappings explicitly.

Configure the handler mapping priority


If multiple view handler mappings are applied, you have to declare priority
to avoid conflict issue.

. Controller

Controller class to handle the web request.

MultiActionController example
Group related actions into a single controller class.

MultiActionController annotation example


Multi-actions controller by using annotation, @RequestMapping, he best
and easy solution.

PropertiesMethodNameResolver example
A flexible method name resolver for the MultiActionController controller
class, it allow to define the mapping between requested URL and method
name explicitly.

ParameterMethodNameResolver example
Another method name resolver for the MultiActionController controller
class, it allow to map URL to method name via requested parameter
name.

ParameterizableViewController example
With ParameterizableViewController, you dont need to hard code the view
name in the controller class anymore, instead, you specify the view name
through the ParameterizableViewControllers viewName property.

4. View Resolver

Resolve view name that returned from the controller class to a physical view page or JSP
page.

InternalResourceViewResolver example
Adding a predefined prefix and suffix to the view name (prefix + view
name + suffix), and generate the final view page URL.

XmlViewResolver example
Puts view beans in XML file.

ResourceBundleViewResolver example
Puts view beans in .properties file.

Configure multiple view resolvers priority


If multiple view resolver strategies are applied, you have to declare
priority to avoid conflict issue.

5. Form Handling

Form handling in Spring MVC.

Form handling example


Form handling in Spring MVC, XML based version.

Form handling annotation example


Form handling in Spring MVC, annotation version.

Handling duplicate form submission


Post/Redirect/Get Design Pattern is the common solution for this
duplicated form submission problem.

RedirectView example
A view which redirect to another absolute, context relative, or current
request relative URL.

Handling multipage / wizard forms


How to handle multipage forms or wizard form.

6. Springs Form Tag Library

Render HTML forms components via Springs form tag.

Textbox example
<form:input /> tag, render a HTML textbox field.

Password example
<form:password /> tag, render a HTML password field.

Textarea example
<form:textarea /> tag, render a HTML textarea field.

Checkbox and Checkboxes example


<form:checkbox />, <form:checkboxes /> tags, render a single or multiple
HTML check boxes.

Radiobutton and Radiobuttons example


<form:radiobutton />, <form:radiobuttons /> tags, render a single or
multiple HTML radio buttons.

Dropdown and list box example


<form:select />, <form:option /> and <form:options /> tags, render a
HTML dropdown box, multiple select box and listbox.

Hidden value example


<form:hidden /> tags, render a HTML hidden value field.

Form errors tag example


<form:errors /> tag , render those form components error messages.

File upload example


File upload handling via Spring MultipartResolver.

7. Integrating Spring MVC with other frameworks

Integrate Spring MVC with others.

Spring 3 MVC and JSR303 @Valid example


Using Hibernate validator (JSR303 implementation) to validate bean in
Spring MVC.

Spring 3 MVC and RSS feed example


Using ROME to generate RSS feed from Spring MVC.

Spring 3 MVC and XML example


Using JAXB to generate XML output from Spring MVC.

Spring 3 MVC and JSON example


Using Jackson to generate JSON output from Spring MVC.

Spring MVC and Excel file via AbstractExcelView


Using AbstractExcelView to export data to Excel file via Apache POI library.

Spring MVC and Excel file via AbstractJExcelView


Using AbstractJExcelView to export data to Excel file via JExcelAPI library.

Spring MVC and PDF file via AbstractPdfView


Using AbstractPdfView to export data to Pdf file via Bruno Lowagies iText
library.

Spring MVC and Log4j integration example


Example to integrate Log4j into the Spring MVC application.

8. FAQs

Some common use cases.

Spring 3 MVC ContentNegotiatingViewResolver example


This view resolver let you determine which view resolver will be returned,
base on reuqested file extension.

Exception handling example


Exception handling in Spring MVC.

Handler interceptors example


Intercept web request through handler interceptors.

Internationalization example
Multiple languages supported in Spring MVC.

10. Common Errors

Spring MVC common errors and solution.

ModelAndViews model value is not displayed in JSP via EL

404 error code is not working in Spring MVC

Cannot change HTTP accept header use a different locale resolution


strategy

Spring MVC failed to convert property value in file upload form

Neither BindingResult nor plain target object for bean name xxx available
as request attribute

ClassNotFoundException : com.sun.syndication.feed.WireFeed

ClassNotFoundException :
com.thoughtworks.xstream.io.HierarchicalStreamReader

Spring version to use in this tutorials :


1. Spring 3.2.8.RELEASE
2. Spring Security 3.2.3.RELEASE
1. Spring Security Examples

Examples to show you how to secure your web application with Spring Security.

Spring Security Hello World XML Example


Spring MVC + Spring Security XML-based project, using the default login
form.

Spring Security Hello World Annotation Example


Spring MVC + Spring Security annotations-based project, using the default
login form.

Spring Security Custom Login Form XML Example


Spring MVC + Spring Security XML-based project, custom login form,
logout function, CSRF protection and in-memory authentication.

Spring Security Custom Login Form Annotation Example


Spring MVC + Spring Security annotations-based project, custom login
form, logout function, CSRF protection and in-memory authentication.

Spring Security Form Login Using Database XML and Annotation Example
Database authentication, Spring Security, JSP taglibs, JDBC, customizes
403 access denied page and etc, both in XML and annotations.

Spring Security : Limit Login Attempts XML and Annotation Example


Lock user accounts if a user tried 3 invalid login attempts.

Spring Security Remember Me Example


Remember me Persistent Token Approach example. Extra : user login
from remember me cookie is unable to perform the update operation.

Spring Security password hashing example


Password encoder with BCrypt algorithm.

Spring Security + Hibernate XML Example


Using Hibernate to load users for database authentication.

Spring Security + Hibernate Annotation Example


Using Hibernate to load users for database authentication

2. FAQs

Some commonly asked questions in Spring Security.

Customize 403 access denied page


Like topic, shows you how to customize a 403 access denied page, using
the error-page attribute and custom handler.

Check if user is from remember me cookie


If authentication == RememberMeAuthenticationToken

Encoded password does not look like BCrypt


Length of password is not enough to store the bcrypt hashing value.

How to get current login username in Spring Security


3 ways to get current login username in Spring Security.

ClassNotFoundException :
org.springframework.security.web.savedrequest.DefaultSavedRequest

Some outdated or obsoleted articlesmay update in future.

Spring Security HTTP basic authentication example


The browser displays a login dialog for authentication.

Spring Security access control example


Example to implement access control or authorization on web application.

Display custom error message in Spring Security


How to override default Spring Security error messages easily.

Spring Security logout example


Simple example to show you how to implement the logout function.

The following Spring Batch tutorials and examples are tested with :
1. Spring Core 3.2.2.RELEASE
2. Spring Batch 2.2.0.RELEASE

P.S Spring Batch is part of the Spring Portfolio.


1. Quick Guide

A simple batch job, and run with command line.

Spring Batch Hello World Example


Short description about Spring batch, and create a job to read data from a
CSV File, process it, and write it to an XML file (JAXB).

Spring Batch TaskletStep example


Example to cleanup the resources after the batch job has completed.

Run Spring Batch Job With CommandLineJobRunner


Run Spring batch job with command line.

2. ItemReader, ItemProcessor, ItemWriter

Few examples to show the use of Spring batch classes to read/write resources (csv, xml and
database).

Spring Batch Example CSV File To MySQL database


Read data from a CSV file and write it into a MySQL database, job meta is
stored in the database.

Spring Batch Example XML File To MongoDB database


Read data from a XML file (XStream) and write it into a nosql database
MongoDB, also unit test the batch job.

Spring Batch Example XML File To CSV File


Read data from a XML file (JAXB2), process with ItemProcessor and write it
into a CSV file. It also shows you how to convert Date and BigDecimal data
type to/from object via JAXB2.

Spring Batch Example MySQL Database To XML


Read data from a MySQL database and write it into an XML file (XStream),
also the use of jobParameters.

Spring Batch MultiResourceItemReader example


A ItemReader to read multiple files.

3. Scheduler

Run batch job with scheduler frameworks.

Spring Batch + Spring TaskScheduler example


Spring TaskScheduler to schedule a batch job to run every 5 seconds.

Spring Batch + Quartz Scheduler example


Integrate Quartz to schedule a batch job to run every 10 seconds.

4. Unit Test

Spring Batch unit test example


How to unit test a batch job or individual steps.

5. Advance

Spring Batch partitioner example


Multiple threads to process range of data.

Spring Batch listener example


Examples to intercept the step execution of a batch job.

6. Spring Batch FAQs

Some common questions and answers in Spring Batch.

How to convert Date in BeanWrapperFieldSetMapper

Spring Batch : A job instance already exists and is complete for


parameters={}

Spring Batch metadata tables are not created automatically?

NoSuchBeanDefinitionException : No qualifying bean of type


JobLauncherTestUtils

jobParameters cannot be found on object of type BeanExpressionContext

Das könnte Ihnen auch gefallen