Spring Study Notes - Copyright © 2010 Gavin Lasnitzki Index   Notes   Objectives

The following notes are very, very heavily based on Jeanne Boyarsky's excellent Spring 3 Certification Study Notes (super big thank you!!).

I have copied / reposted them, changed the formatting and added where I thought appropriate.

I believe these notes cover most of the material (and much of it in more depth than the exam). The exam focuses more on high level features / concepts (i.e. what can and can't feature X do, can this be applied to private methods, etc) than detailed syntax and implementation. Topics with "(Jeanne)" were added by Jeanne and ones with (Gavin) were added by me. As Jeanne indicated, most of these are not required for the certification. However, I added these topics before I did the exam and have not reviewed them after the exam, so please take it as a guide (and study more material rather than less!!).

Breakdown (as per Jeanne Boyarsky's Spring 3.X Certification Experiences) is:

  • Container and test (20)
  • AOP (10)
  • JDBC (3)
  • Transactions (4)
  • Web (2)
  • REST (2)
  • Remoting  (2)
  • Security (2)
  • JMS (2)
  • JMX (2)


Spring Reference Docs

Spring Framework 3.0.x



This product includes software developed by the Spring Framework Project (http://www.springframework.org).This is a work derived from the Spring Reference Documentation (see Notice.txt and License.txt).


Spring 3.0 Study Notes

1. Container

1.1 General

1.1.1 The potential advantages of using Spring's dependency injection?


  • Loosely coupled code
  • Autowire
  • Dependency checking

1.1.2 Dependency injection in XML, using constructor


Only works if there is no ambiguity in args

Use the following attributes to reduce ambiguity:

  • "type" matching by specifying argument type
  • "index" by specifying position (zero based)

1.1.3 Dependency injection in XML, using setter injection


1.1.4 Scopes


  • Singleton (default)
  • Prototype
  • Web (session, request)

1.2 Lifecycle

1.2.1 How to declare an initialization method in a Spring bean [in XML]?


1.2.2 How to declare a destroy method in a Spring bean [in XML]?


1.2.3 Default bean instantiation policy: when are beans instantiated?

For Singleton, when app context is created / parsed

To specify instantiation policy

  • Use "lazy-init" on the "bean" element
  • Use the "default-lazy-init" on the "beans" element

1) Load all bean definitions to create an ordered graph
- The container tries to set properties and resolve dependencies as late as possible.
2) Instantiate and run BeanFactoryPostProcessors (can update bean definitions here)
3) Instantiate each bean
4) Set properties
5) BeanPostProcessors (#postProcessBeforeInitialization)
6) @PostConstruct
7) InitializingBean (#afterPropertiesSet)
8) Call init-method
9) BeanPostProcessors (#postProcessAfterInitialization)
10) @PreDestroy
11) DisposableBean (#destroy)
12) Call destroy-method

Mem: context, BFPP, new, set, BPP#before, init[@PostConstruct, Init#after, init-method], BPP#after, dispose[@PreDestroy, Disp#destroy, destroy-method]

Mem: init / destroy order is: (@) annotation, (#) interface method, (-) xml attribute

1.2.4 What are BeanFactoryPostProcessors and BeanPostProcessors? When are they called in the startup process?


  • Each processor is called once per xml (i.e per application context)
  • Before beans are instantiated
  • Can change bean configuration / definitions
  • If BeanFactoryPostProcessors are marked as being lazily-initialized they will NOT be instantiated and will NOT apply their logic.


  • Each processor is called once per bean
  • Can run before / after a bean is initialised

1.2.5 What is a BeanFactory? (Jeanne)

Underlying basis for Spring's IoC functionality

1.3 Annotations

1.3.1 Enabling component-scanning

<context:component-scan />

Looks for @Component (general), @Controller (web), @Repository (dao) and @Service (service)
Can set context:include-filter and context:exclude-filter elements     
Turns on <context:annotation-config />


1.3.2 Behavior of the annotation @Autowired with regards to field injection, constructor injection and method injection


  • no: (default) No auto-wiring will be performed. You must wire the dependencies explicitly.
  • byName: For each bean property, wire a bean with the same name as the property.
  • byType: For each bean property, wire a bean whose type is compatible with that of the property.
  • constructor: If a default constructor with no argument is found, the dependencies will be auto-wired by type. Otherwise, they will be auto-wired by constructor.

Default autowire mode is "no"

If > 1 match, throws exception (unless injecting into Collection).
If no matches, autowiring fails unless using @Required or "required" attribute

May be applied to:

  • setter methods
  • methods with arbitrary names and/or multiple arguments
  • constructors
  • fields (even private ones)
  • arrays (whereby all beans of a particular type from the ApplicationContext are injected)
  • typed collections
  • typed maps (as long as the key is a java.lang.String )


1.3.3 How does the @Qualifier annotation complement the use of @Autowired?


 For a fallback match, the bean name is considered as a default qualifier value.

Chooses specific bean when more than one exists of same type

1.3.4 What is the role of the @PostConstruct and @PreDestroy annotations?

Similar to init-method and destroy-method

1.3.5 Enabling the scanning of annotations such as @Required and @PreDestroy?

 Use <context:annotation-config /> for (Spring's @Required and @Autowired, JSR 250's @PostConstruct, @PreDestroy and @Resource, PA's @PersistenceContext and @PersistenceUnit)

Or <context:component-scan /> for (@Component, etc)

@Required goes on setters, not fields
@PostConstruct, @PreDestroy goes on methods

1.3.6 Other interesting annotations (Jeanne)

@Value("#{ systemProperties['user.region'] }")

Scheduled tasks

  • @Scheduled(fixedDelay=5000)
  • @Async

1.3.7 SpEL (Gavin)


  • Code: (new SpelExpressionParser()).parseExpression("numberGuess.randomNumber")getValue(target)
  • Xml: value="#{numberGuess.randomNumber}"/>
  • Annotation: @Value("#{numberGuess.randomNumber}")

1.4 Miscellaneous

1.4.1 How to inject scalar/literal values into Spring beans?


  • Element: <property name="email"><value>b@b.com</value></property>
  • Attribute: <property name="email" value="b@b.com" />
  • p namespace: <bean ... p:email="b@b.com" />

Empty: <property name="email"><value/></property>

Null: <property name="a"><null /></property>

Compound property names: person.address.streetNo

1.4.2 How to refer to a collection in a Spring bean definition?











The value of a map key or value, or a set value, can also again be any of the following elements:
bean | ref | idref | list | set | map | props | value | null

If you need to refer to this outside a <bean /> or need to specify list/set/map type, use util namespace (i.e. util:list)



Use the "parent" attribute to inherit (and merge entries) from a parent collection.

Strongly typed collections

  • Entries will be converted to the appropriate type prior to being added to the Collection

1.4.3 How to create an ApplicationContext?

Supports multiple resources

1.4.4 What are the resource prefixes that can be used?


1.4.5 How to refer to a Spring configuration file inside a package?


1.4.6 The different implementations of ApplicationContext that can be used in an application


  • Defaults to classpath:
  • Starts looking from root of classpath regardless of whether specify "/"


  • Defaults to file:
  • Uses relative path even if specify "/", but "file:/mine" forces an absolute path


  • Defaults to file: in /WEB-INF/applicationContext.xml
  • Uses path relative to web application

1.4.7 How to externalize constants from a Spring XML configuration file into a .properties file?



1.4.8 Purpose and usage of bean definition inheritance

Extract common bean setup into one "super" bean to reduce duplicate setup code

A bean without a class or factory is implicitly abstract.

The "abstract" attribute is optional but good practice as it prevents the bean from being instantiated by the container.

The parent class does not have to be abstract and can still be instantiated using the new operator.

1.4.9 How to use the p namespace?

Set property as attributes


1.4.10 Difference between "id" and "name" attributes in the <bean> tag

Identifiers (id and/or name) must be unique within the container that hosts the bean.


  • Must be unique
  • Limits the characters that are legal


  • Can specify multiple names separated by comma, semicolon or space
  • Allows more characters in name such as slashes

You are not required to supply a name or id for a bean. If no name or id is supplied explicitly, the container generates a unique name for that bean. However, if you want to refer to that bean by name you must provide a name.

1.4.11 Purpose of the <aop:scoped-proxy/> tag

If need to inject a bean with request/session scope into a bean with singleton scope,  the proxy intercepts it and makes sure you get the right bean for each call.


1.4.12 How does FactoryBean work (Optional, From 2.5 sample questions)?

Class name in bean definition (in xml) is that of the factory

Setters called on the factory rather than the created bean

Bean id maps to type returned by factory's getObject() method

To get the actual FactoryBean instance from the container and not the bean it produces, you preface the bean id with the ampersand symbol


  • Invoking getBean("myBean") on the container returns the product of the FactoryBean
  • Invoking getBean("&myBean") returns the FactoryBean instance itself

To get a bean programatically from the ApplicationContext:

  • <T> T getBean(Class<T> requiredType) - Return the bean instance that uniquely matches the given object type, if any.
  • Object getBean(String name) - Return an instance, which may be shared or independent, of the specified bean.

1.4.13 How to inject using a factory method (Jeanne)?

Instance (non-static) factory method: specify "factory-bean" and "factory-method" attributes

Static factory method: specify "class" and "factory-method" attributes 

Use <constructor-arg> to pass parameters

1.4.14 How to use a PropertyEditor (Jeanne)?

Extend PropertyEditorSupport and implement setAsText(String text) and String getAsText()

1.4.15 Splitting the XML (Jeanne)

<import resource="local path" />

Prefer "multiple resource locations" as configs are unaware of each other

Relative to the definition file

Use classpath:/.. or file:.. if need an absolute path

1.4.16 Other util namespace items (Jeanne)

<util:constant static-field="fully qualified name" />

<util:properties location="property file" />

1.4.17 Spring EL (Jeanne)


1.4.18 References to other beans (collaborators) (Gavin)  

<ref />
Use the "bean", "local" or the "parent" attribute to control lookup context

Inner beans

  • A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.
  • Anonymous prototypes (The "scope" flag and any "id" or "name" attribute are effectively ignored.)   


1.4.19 Autowire (Gavin)

Multiple matches

  • Use "autowire-candidate" attribute, "default-autowire-candidates" or "primary" attribute

1.5 JavaConfig

1.5.1 Usage of the @Bean and @Configuration annotations


 Declared on a method that creates a bean in a Java based configuration.
Takes properties

  • initMethod (redundant because can call method)
  • destroyMethod
  • name (aliases)
  • autowire (defaults to no)


  • Declares a class to be a Java based configuration
  • Must have default constructor


  • Used if want to change scope


  • Used if want to specify which bean to inject

@Import to reference another @Configuration

  • Used because you can't just call it directly as calls must be in the correct order in dependency graph

1.5.2 How to write a bean definition method?

@Bean public String myBean() { return "hi"; }

Defines a String bean with the id "myBean" and the value "hi"

1.6 Testing

Spring's integration testing support has the following goals:

  • Spring IoC container caching (by fixture) between test execution.
  • Dependency Injection of test fixture instances.
  • Transaction management appropriate to integration testing.
  • Spring-specific support classes that are useful in writing integration tests.

1.6.1 How to use Spring's integration testing support in a JUnit 4 test?

Test needs to implement ApplicationContextAware, configure the DependencyInjectionTestExecutionListener or use the @RunsWith

@RunWith(SpringJUnit4ClassRunner). Provides the benefits of the TestContext framework

@ContextConfiguration("config.xml") or @ContextConfiguration(locations={"config.xml"})

  • Defaults to the test's class name and an "-context.xml" suffice (using the GenericXmlContextLoader) i.e. MyTest-context.xml    
  • The "inheritLocations" attribute of the annotation (default to true) inherits (appended to current list) the super-classes locations
  • The context is cached across test fixtures unless you use @DirtiesContext.

1.6.2 How to declare that a test should run in a transaction in spring-enabled JUnit 4?

By default, the framework will create and roll back a transaction for each test.

@TransactionConfiguration  - Placed on class to set transaction manager and default rollback policy

@Transactional - on class or method, can set prorogation/isolation/etc

@Rollback - on class or method

@BeforeTransaction (@Before is inside txn)

@AfterTransaction (@After is outside txn)

1.6.3 Differences between a Unit test and an Integration test.  Which of them is supposed to interact with Spring?

  • Unit test tests one class in isolation with mocks.
  • Integration test tests multiple classes together.
  • Only integration tests interact with Spring.


2. AOP

2.1 Recommendations

2.1.1 In order to work successfully with AOP, it is important to understand the theory behind the scenes. Consequently you should understand the four main AOP keywords taught in this course: Aspect, Advice, Pointcut, Joinpoint.

Aspect: a modularization of a concern that cuts across multiple classes (packaged advice and pointcut).

Joinpoint: a point during the execution of a program, such as the execution of a method or the handling of an exception.

Advice: action taken by an aspect at a particular join point (code to execute).

Pointcut: a predicate that matches join points (expression to identify join point).  The place in code where code can be injected.  In Spring this is just before/after methods.

MEM: For Aspect A when program reaches a Joinpoint that matches Pointcut P then execute Advice X

Targeted object: object being advised

AOP proxy: object created by AOP to implement the aspect contracts

2.2 Pointcuts

2.2.1 You should have a deep understanding of pointcut expressions. It is important to understand all pointcut examples in the slides (apart from the ones in the "advanced topics" section at the end of the module).


MEM: execution([Modifiers such as annotations] ReturnType [FullyQualifiedClassName.] MethodName ([Arguments]) [throws ExceptionType])
[public] String [a.b.c.MyClass] [doWork](String) throws RuntimeException

".." means 0 or more (arguments or packages)
"*" means exactly 1 of anything (argument, package name, etc)
"+" means this class or any implementors (no matter how deep)
&&, ||, ! (and, or and not)

Other expressions I think are outside the scope of the exam:

  • within - certain types
  • bean - id or name of Spring bean
  • target - target object is an instance of the given type
  • this - bean ref is an instance of the given type
  • args - args are instances of given type
  • @target, @args, @within, @annotation   .. has annotation of..     


  • @Pointcut("execution(* transfer(..))") // the pointcut expression
  • private void anyOldTransfer() {} // the pointcut signature

Pointcut will be matched against public methods only!

2.3 Advice

2.3.1 Different kinds of Advice. How do they differ from each other?

Use either ref pointcut or in-place point cut

  • Example of ref: @Before("x.y.myOperation()") where @Pointcut("within(x.y.*)") private void myOperation(){}
  • Example of in-place: @Before("within(x.y.*)")


  • Before call code
  • Aborts if throw exception
  • Can prevent target method being called


  • After unconditionally
  • Handles normal and exception return
  • Can change return value or throw an exception


  • After on success only
  • Can change return value but it is not possible to return a totally different reference when using after-returning advice.
  • Use:


  • After on failure only
  • Can change exception type thrown
  • Use:


  • Surrounds
  • Takes ProceedingJoinPoint, can intercept call or ignore exception
  • First parameter of the advice method must be of type ProceedingJoinPoint
  • Call proceed() on the ProceedingJoinPoint to execute the method

Prefer least powerful advice that can do the job

Declare a JoinPoint parameter to get access to methods like: getArgs, getTarget, etc

Use binding for of args:

2.4 Configuration

2.4.1 Enabling the detection of @Aspect annotated classes.

<aop:aspectj-autoproxy />

2.4.2 Is it possible to set up Spring AOP using XML configuration only (as opposed to annotations)?



2.5 Proxies

2.5.1 When are they generated in the Spring lifecycle?

Bean Post Processing

2.5.2 How do they resemble the target object that they advice?

They have the same public interface if there is an interface. 
You must have an interface or non-final class to create a proxy.


  • Non-final class: (MyBean) ctx.getBean("myBean") -> exception as proxy will be a different type
  • Implements interface: (MyInterface) ctx.getBean("myBean") -> no exception

2.5.3 What limitations does Spring-AOP's proxy-based approach have?

Can only be used for methods
Limited pointcut syntax
Doesn't get called if caller makes direct calls
Final classes cannot have aspects applied

2.5.4 How are aspects detected by Spring AOP? (Gavin)

Use @Component (with class path scanning)  or register with: <bean id="myAspect" class="org.xyz.NotVeryUsefulAspect">...

3 Data Access and transactions


3.1 General

3.1.1 The rationale for having the DataAccessException hierarchy. Definition of a DataSource in the Spring configuration

DataAccessException explained...

  • Runtime exception – doesn't force developers to catch and rethrow
  • Consistent/non-vendor specific messages – isolates from database
  • Clearer names – easy to catch and handle specific errors

Datasource definition

  • If in JNDI: <jee:jndi-lookup id="ds" jndi-name="java:comp/env/jdbc/DS" />
  • If not in JNDI: <bean id="ds" class="DataSourceClass" />

3.2 The JdbcTemplate

3.2.1 Usage of the JdbcTemplate with regards to exception handling

The JdbcTemplate is stateful, in that it maintains a reference to a DataSource, but this state is not conversational state. Instances of the JdbcTemplate class are thread-safe once configured.

JdbcTemplate jdbc = new JdbcTemplate(datasource);

Callback methods throw SQL Exception and Spring converts to DataAccessException

Use NamedParameterJdbcTemplate when want param names (i.e "... where x=:myparam") rather than classic placeholder (i.e "... where x=?") 

Use SimpleJdbcTemplate (JDK 1.5) which delegates to JDBCTemplate and makes use of some of the JDK 1.5 features.

  • getJdbcOperations, getNamedParameterJdbcOperations to get underlying template  
  • Note: As of Spring 3, JdbcTemplate uses JDK 1.5 features such as var-args

Spring and you

  • (You) Define connection parameters.
  • (Spring) Open the connection. 
  • (You) Specify the SQL statement.    
  • (You) Declare parameters and provide parameter values.  
  • (Spring) Prepare and execute the statement.
  • (Spring) Set up the loop to iterate through the results (if any).   
  • (You) Do the work for each iteration.
  • (Spring) Process any exception.
  • (Spring) Handle transactions.   
  • (Spring) Close the connection, statement and resultset.

3.2.2 With regard to querying [generically]

jdbc.queryForInt("select count(*) from table");

Generic queryFor____ methods available for:

  • Object –  convert to specified type
  • Map – convert to a map with the column name as key
  • List – list of maps

3.2.3 With regard to querying [with parameters]


SqlParameterSource interface allows parameters to be retrieved from different sources

3.2.4 With regard to result set parsing [when need to map to custom object]


For list: jdbc.query(sql, mapper);

For single row: jdbc.queryForObject(sql, mapper);

3.2.5 With regard to result set parsing [when need to write out data to file but not return it]


jdbc.query(sql, handler); 

3.2.6 With regard to result set parsing [merging rows into a list or other return object]


 jdbc.query(sql, extractor);

3.2.7 With regard to querying [for insert/update/delete row]


jdbc.update(PreparedStatementCreator, KeyHolder)

3.2.8 With regard to running DDL


3.2.9 With regard to batch updates


with jdbcTemplate.batchUpdate(sql, setter) or pass Object[] as second parameter

3.2.10 With regard to when you need even more control


PreparedStatementCreator and CallableStatementCreator create from connection

SimpleJdbcInsert and SimpleJdbcCall use a map rather than callbacks relying on database metadata.

3.3 Hibernate

3.3.1 Configuration of a SessionFactoryBean in xml [listing each entity]

LocalSessionFactoryBean supports a list of Hibernate XML mapping locations (use mappingLocations).

AnnotationSessionFactoryBean extends LocalSessionFactoryBean  and adds support for a list of annotated classes (use "annotatedClasses") or packages to scan (inc wildcards, use "packagesToScan").


3.3.2 Configuration of a SessionFactoryBean in xml [scanning for annotations]



3.3.3 Configuration of a SessionFactoryBean in xml [listing each hbm file]



3.3.4 What are benefits of  transactions for Hibernate? (Jeanne)

Read only transactions prevent Hibernate from flushing session

3.4 Transactions

3.4.1 Configuration to declare a local transaction manager


HibernateTransactionManager – supports Hibernate and JDBC

JdbcTransactionManager – only supports JDBC

3.4.2 Configuration to declare a JTA transaction manager

<bean id="mgr" class="org.springframework.transaction.jta.JtaTransactionManager" />

3.4.3 Declarative transaction management with Spring [creating the transaction manager]

If server provides JTA: <tx:jta-transaction-manager />


3.4.4 Declarative transaction management with Spring (xml)


3.4.5 Declarative transaction management with Spring (annotations)

@Transactional on public methods or class (not recommend on interfaces b/c not all proxies will take them). 

@Transactional on non-public methods will not give error, but will not be in transaction.

<tx:annotation-driven /> to enable annotation scanning

3.4.6 Usage of TransactionTemplate for programmatic transaction management (you simply need to understand a basic example based on the TransactionTemplate).

Takes transaction manager in constructor.

Passes TransactionStatus to TransactionCallback which lets you call status.setRollbackOnly()


3.4.7 Transactions and exception management: what is the default rollback policy?

Rollback for a RuntimeException

3.4.8 Can it be overridden?


For the @Transactional annotation, specify rollbackFor or noRollbackFor when passing Class or rollbackForClassname/noRollbackForClassname when passing Strings

3.4.9 The @Transactional annotation: what are the main attributes that can be used for a transaction definition?

timeout – specified in seconds
readOnly – true or false
propagation – Propagation.REQUIRES_NEW, REQUIRED, etc
rollbackFor – list of exceptions
noRollbackFor – list of exceptions

3.4.10 Can this annotation also be used with a JTA Transaction Manager?


3.4.11 Regarding propagation modes, what is the difference between PROPAGATION_REQUIRED and PROPAGATION_REQUIRES_NEW

REQUIRED (default)

  • If there’s an existing transaction in progress, the current method should run within this transaction.
  • Otherwise, it should start a new transaction and run within its own transaction.


  • The current method must start a new transaction and run within its own transaction.
  • If there’s an existing transaction in progress, it should be suspended.


  • If there’s an existing transaction in progress, the current method can run within this transaction.
  • Otherwise, it is not necessary to run within a transaction.


  • The current method should not run within a transaction.
  • If there’s an existing transaction in progress, it should be suspended.


  • The current method must run within a transaction.
  • If there’s no existing transaction in progress, an exception will be thrown.


  • The current method should not run within a transaction.
  • If there’s an existing transaction in progress, an exception will be thrown.


  • If there’s an existing transaction in progress, the current method should run within the nested transaction (supported by the JDBC 3.0 save point feature) of this transaction.
  • Otherwise, it should start a new transaction and run within its own transaction.
  • This feature is unique to Spring

Trick: If methodA calls methodB directly, the transaction attributes of methodB are NOT used.

3.4.12 Regarding isolation levels, what is the difference between READ_COMMITTED and READ_UNCOMMITTED?

The problem..

Dirty read:
T1 Read
T2 Update
T1 Read will be temporary and invalid.
T2 Rollback

Nonrepeatable read:
T1 Read
T2 Update
T1 Read value will be different

Phantom read:
T1 Read
T2 Insert
T1 Read will contain additional rows.

Lost updates:
T1 Read
T2 Read
T1 Update
T2 Update based on invalid Read state

The options...
Uses the default isolation level of the underlying database.
For most databases, the default isolation level is READ_COMMITTED.

Allows a transaction to read uncommitted changes by other transactions.
The dirty read, nonrepeatable read, and phantom read problems may occur.

Allows a transaction to read only those changes that have been committed by other transactions.
The dirty read problem can be avoided, but the nonrepeatable read and phantom read problems may still occur.

Ensures that a transaction can read identical values from a field multiple times.
For the duration of this transaction, updates made by other transactions to this field are prohibited.
The dirty read and nonrepeatable read problems can be avoided, but the phantom read problem may still occur.

Ensures that a transaction can read identical rows from a table multiple times.
For the duration of this transaction, inserts, updates, and deletes made by other transactions to this table are prohibited.
All the concurrency problems can be avoided, but the performance will be low.

4. Spring MVC and REST

4.1 General configuration

4.1.1  This module shows how to configure a ViewResolver, a HandlerMapping and the DispatcherServlet.  You won't be asked any question on how to configure those classes.  However, you need to know what the goal of each of those components is.


View Resolver: Maps returned view name to view implementation.  All handler methods in the Spring Web MVC controllers must resolve to a logical view name.

  • Explicitly (e.g., by returning a String, View, or ModelAndView). They can also return null/void (to use default view) or a concrete class such as new JstlView(path)
  • Implicitly (i.e., based on conventions)

View resolvers

  • AbstractCachingViewResolver - caches view
  • XMLViewResolver - mapping config from xml file
  • ResourceBundleViewResolver - mapping from property bundle file
  • UrlBasedViewResolver - maps urls directly to views
  • InternalResourceViewResolver - extends UrlBasedViewResolver, maps to servlets / jsps
  • FreeMarkerViewResolver - extends UrlBasedViewResolver
  • ContentNegotiatingViewResolver - maps based on request file name or Accept header  

Can be chained (using the "order" attribute). InternalResourceViewResolver  must be last

RedirectView or "redirect:"

Handler Mapping: Identifies correct controller to call.  Spring 3 uses the default one which goes by the @RequestMapping annotation defined in the @Controller.  Can be overriden (in xml) if required

Dispatcher Servlet: Front controller delegating to web infrastructure beans (handler mappings, view resolvers, type converters) and calling controllers/views

Handler Mapping(Request) returns Controller
Controller(Request) returns ModelAndView
View Resolver(View Name) returns View
View(Model) returns Response
returns Response 

4.1.2 You also need to understand the relationship between a DispatcherServlet ApplicationContext and a root ApplicationContext.

DispatcherServletApplicationContext can see the root context's configuration, but the root context can not see DispatchServletApplicationContext

DispatchServletApplicationContext can override root context beans

4.1.3 How access app context from a servlet (Jeanne)


4.1.4 How turn on annotation scanning (Jeanne)

<mvc:annotation-driven />  -  Registers the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter beans that are required for Spring MVC to dispatch requests to @Controllers.

<context:component-scan /> - To enable autodetection of such annotated controllers (as well as other stereotype components). 

4.2 Controllers

4.2.1 Bootstrapping a root WebApplicationContext using the ContextLoaderListener

The DispatcherServlet takes a contextConfigLocation parameter in the web.xml or uses the default of name-servlet.xml

Also need to define listener so it loads the root ApplicationContext before initializing the servlet.


Loads from: /WEB-INF/applicationContext.xml   

To load a specific file, use:

4.2.2 General usage of the @Controller annotations

Annotates a class containing @RequestMapping on methods returning ModelAndView, String, void, etc.

4.2.3 General usage of the @RequestMapping annotations

Takes value of path of URL to match on method level and optionally class level adding slashes as needed. 
Combined, they form the absolute URL path including Ant style wildcards. 
Can also pass method=RequestMethod.GET (or the like) to restrict by type or filter by params/headers.

You can declare @RequestMapping on both the class/method level or just the method level. The method level is key because it tells Spring the method can handle requests.

Maps "/appointments/new" to getNewForm()

URI Template


  • Ant syle globs: @RequestMapping("/myPath/*/pets/{petId}")
  • Parameter conditions: @RequestMapping(value = "/pets/{petId}", params="myParam=myValue")
  • Header conditions: @RequestMapping(value = "/pets", method = RequestMethod.POST, headers="content-type=text/*")

4.2.4 A method annotated with @RequestMapping can return a String. What does it refer to?

The view name. 

 Or more specifically the name passed to the view resolver to determine the view name.  For example, one can add a prefix/suffix to all strings returned.

4.2.5 What are the main parameter types that this method can accept? (based on what you've seen in the class)

Servlet API: HttpSession, HttpServletRequest, HttpServletResponse
Stream: InputStream, Reader, OutputStream, Writer
Annotated: @PathVariable, @RequestParam, @RequestHeader, @RequestBody
Model: Map, Model, ModelMap
Command or Form objects 

4.2.6 Goal of the @RequestParam annotation

To map request parameters to method parameters for use in the controller's methods. 

Can pass parameter name if doesn't match one in method.

4.2.7 Return types of handler method (Gavin)

Model and/ or View: ModelAndView, Model, Map, View
String (logical view name)
void (if the method handles the response directly)
Other: Single model with name based on the class name

4.2.8 Configuring Spring MVC (Gavin)

XML schema
<mvc:annotation-driven />, <mvc:interceptors />      

4.2.9 Does Spring handle Multipart request? (Gavin)

If you specify a multipart file resolver, the request is inspected for multiparts.
If multiparts are found, the request is wrapped in a MultipartHttpServletRequest for further processing by other elements in the process.
In the controller, use: @RequestParam("myParam") MultipartFile file 


4.3 REST

4.3.1 Differences between GET, POST, PUT and DELETE

Revolves around the use of the Spring MVC annotations @RequestMapping and @PathVariable

  • GET = select (read only)
  • POST = create
  • PUT = update
  • DELETE = delete

4.3.2 Usage of the @PathVariable annotation

Maps parts of the url in @RequestMapping to a parameter.  For example the URL /account/{id} goes with @PathVariable id in the method signature.

4.3.3 What is the RestTemplate?

Programmatic client for calling RESTful URLs.

4.3.4 How should it be used?

String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class,"42", "21");

RestTemplate t = new RestTemplate();
t.getForObject(uri, MyResponse.class, id);
t.postForObject(url, request, MyResponse.class, var1, var2) or t.postForLocation(url, request, var1, var2)
t.put(uri, mine);

HttpMessageConverter to convert to / from HTTP   

4.3.5 Purpose of the @ResponseStatus Annotation

Send an HTTP response code with the response. 
If defined on the method, sends that header. 
If defined on an  exception, only sends if that error occurs.
For example, @ResponseStatus(HttpStatus.CREATED)
An empty body can be used for REST so no view is used.
Annotation can go on @RequestMapping method or an exception class.

4.3.6 Purpose of the @ExceptionHandler Annotation  

Specify which method is invoked when an exception of a specific type is thrown during the execution of controller methods
If cannot annotate the actual exception, defines a response status in controller.

 For example,

  • @ResponseStatus(HttpStatus.NOT_FOUND)
  • @ExceptionHandler({MyException.class})

4.3.7 What are HttpMessageConverters (Jeanne)

Objects passed to and returned from the methods getForObject(), postForLocation(), and put() are converted to HTTP requests and from HTTP responses by HttpMessageConverters.
Concrete implementations for the main media (mime) types are provided in the framework and are registered by default with the RestTemplate on the client-side and with AnnotationMethodHandlerAdapter on the server-side.

Use @RequestBody to map param
Use @ResponseBody to map return value

5. Advanced topics

5.1 Remoting   

5.1.1 Advantages of using Spring Remoting rather than plain RMI?

Hide plumbing/complexity
Support multiple protocols        
Simplify things when both ends of remote call run Spring

5.1.2 Goal of the RMI Service Exporter

Handle server side of RMI interaction
Bind to registry
Expose endpoint (used for everything except EJB; EJB already has mechanism to export remote)

5.1.3 General configuration of the RMI Service Exporter

<bean class="org.springframework.remoting.rmi.RmiServiceExporter"></bean> and set properties:

  • serviceName (name in registry)     
  • serviceInterface (interface classname)
  • service (reference to POJO implementing serviceInterface)


5.1.4 Goal of RMI Proxy Generator

Handle client side of RMI interaction
Communicate with endpoint
Convert remote exception to runtime exception
Can treat remote EJBs as POJOs

5.1.5 General configuration of RMI Proxy Generator

<bean class="org.springframework.remoting.rmi.RmiProxyFactoryBean></bean>  and set properties:

  • serviceInterface (interface classname)
  • serviceUrl (rmi://server:port/serviceName)


5.1.6 Difference between the RMI Service Exporter and the HttpInvoker

HttpInvoker uses HTTP POST while RMI one uses RMI. 

To use create bean HttpInvokerServiceExporter with service (reference to POJO implementing serviceInterface) and service interface (interface classname).

The serviceName is specified as the name of the bean because default is to use BeanNameUrlHandlerMapping.

 Also create bean HttpInvokerProxyFactoryBean with same properties as for RMI.

5.1.7 Does the HttpInvoker require to run a web server on the client side? On the server side?

Hessian, Burlap, HttpInvoker need a web server on the server side, but not the client side.

5.1.8 What about Hessian and Burlap? (Jeanne)

To use, see instructions for HttpInvoker.
Hessian is binary, Burlap is textual. 
Proprietary approach to serialization

5.2 Security

5.2.1 What is the "Security filter chain" used in Spring Security?

Basic concepts (Gavin)

  • Authentication is the process of verifying a principal's identity against what it claims to be.
  • A principal can be a user, a device, or a system, but most typically, it's a user.
  • A principal has to provide evidence of identity to be authenticated.
  • This evidence is called a credential, which is usually a password when the target principal is a user.
  • Authorization is the process of granting authorities to an authenticated user so that this user is allowed to access particular resources.
  • The authorization process must be performed after the authentication process.
  • Typically, authorities are granted in terms of roles.
  • Access control means controlling access to an application's resources.
  • It entails making a decision on whether a user is allowed to access a resource.
  • This decision is called an access control decision, and it's made by comparing the resource's access attributes with the user's granted authorities or other characteristics.

Series of servlet filters that must be passed before/after resource is accessed.
These include

  • loading HttpSession's context
  • logging out if needed
  • authenticating if needed
  • throwing proper exception (after only)
  • checking role


5.2.3 Can add your own or replace an existing filter.

In web.xml:

5.2.4 Syntax to configure Spring Security to intercept particular URLs?  (you need to have a good understanding of the various examples using intercept-url in the course)


Always end url with a "*" to prevent hackers skipping the check by adding extra request parameters       

Pattern uses Ant syntax (** is any level of directories), can change to reg exp

Access can get IS_AUTHENTICATED_FULLY or a list of roles

If more than one intercept-url, matched top to bottom

filters="none" - no security applied

Anonymous users have the ROLE_ANONYMOUS role

5.2.5 Syntax to configure method level security using @Secured (Spring) or @RolesAllowed (JSR)

<security:global-method-security secured-annotations="enabled" /> and use @Secured("role1") to pass allowed roles

or <security:global-method-security jsr250-annotations="enabled" /> and use @RolesAllowed("role1") to pass allowed roles

or without annotations:

or secure a bean with a list of method names using

5.2.6 Possible mechanisms to store user details: database? LDAP? Others?


Other user services
Database: <security:jdbc-user-service data-source-ref="ds" />
In memory: <security:user-service properties="a.properties" />
Others include: In xml file, In properties file, LDAP, JAAS, SSO, Open Id

5.2.7. When working with an authentication provider, is it possible to use a password encoder?

Yes.  <security:password-encoder hash="abc" />

5.2.8 In the security tag library, what is the purpose of the <security:authorize /> tag?

To say what roles are permitted access to a section of the JSP.
<security:authorize ifAnyGranted="roles">do stuff</security:authorize>
set propeties: ifAnyGranted, ifAllGranted

5.2.9 What does auto-config Include? (Gavin)

 Shorthand for

Use <form-login />  and set properties: login-pages, default-target-url, authentication-failure-url 

Use <logout /> and set properties: logout-success-url

Use <anonymous username="guest" granted-authority="ROLE_GUEST" /> to setup the anon user

Use <remember-me /> to setup Remember-Me Support

5.3 JMS

5.3.1 Purpose of the JmsTemplate

Simplify usage of JMS, reduce boilerplate code, handle exceptions, etc

5.3.2 What properties does JmsTemplate require (Jeanne)?

Instances of the JmsTemplate class are thread-safe once configured.

Connection Factory

  • SingleConnectionFactory
  • CachingConnectionFactory

Use "defaultDestination" – Destination does not need to be specified for each send / receive call.

  • Default Destination can be a Spring bean reference (defaultDestination) or a name (defaultDestinationName)  
  • DestinationResolver – map destination name to actual destination. Used to determine destination in complex situations (dynamic destinations)

  or pass in destination as send / receive method parameter.     

5.3.3 What callbacks are available (Jeanne)

No callback, use convertAndSend() and receiveAndConvert(). These methods delegate conversion to the MessageConverter bean (set on the JmsTemplate) to convert the message.

MessageCreator - if need to map object to/from Message for nonstandard type


MessagePostProcessor interface gives you access to the message after it has been converted

SessionCallback and ProducerCallback - Use jmsTemplate.execute()

5.3.4 How to send a message (Jeanne)

template.convertAndSend();  - takes message and optional Destination name/object (uses default if not specified)

Or call send() if need MessageCreator callback

Or execute() if need advanced callback during template

All send methods put message on queue and resume

5.3.5 How to receive a message (Synchronous)?

Use JMSTemplate

  • template.receive() take optional destination
  • receiveAndConvert() if set MessageConverter

All receive methods are blocking / synchronous

5.3.6 How to declare a JMS Listener (Asynchronous)?

Use Message-Driven POJOs

POJO's must be thread-safe

Implement javax.jms.MessageListener (J2EE) or SessionAwareMessageListener (Spring-specific) or using the MessageListenerAdapter class

Set delegate, defaultListenerMethod properties
POJO "defaultListenerMethod" method must accept one of the following types as its sole method argument: Message, String, Map, byte[], Serializable



Define a container

Extend JmsGatewaySupport


  • SimpleMessageListenerContainer - non-txn aware, close to the spirit of the standalone JMS specification
  • DefaultMessageListenerContainer - txn aware (including in (XA) externally managed transactions)

5.3.7 Can a JMS Listener be a POJO?

 Yes, just register in XML inside a listener-container:


  • destination is where we listen for a message
  • response-destination is needed if the method doesn't return void

5.3.8 Is it possible to run JMS inside a plain Servlet container without full Java EE support (such as Tomcat or Jetty)?

Can use SimpleMessageListenerContainer for basics or  DefaultMessageListenerContainer if need transactions

Register using a MessageListenerContainer . Takes as properties: connectionFactory, destination, messageListener

5.3.9 What configuration is necessary (Jeanne)

Create connection factory and queues by creating bean for standalone or <jee:jndi-lookup jndi-name="jms/aaa" />

Can wrap with CachingConnectionFactory if need caching

5.4 JMX

5.4.1 Role of the MBeanExporter

Expose POJO as MBean. This class is responsible for taking your Spring beans and registering them with a JMX MBeanServer.

5.4.2 Using Spring JMX, is it possible to export a POJO as an MBean?

Yes.  Register as a bean and use MBeanExporter


Bean is exposed as an MBean under the ObjectName bean:name=mine

By default, the Spring MBeanExporter exports all public properties of a bean as MBean attributes and all public methods as MBean operations.
Use an MBeanInfoAssembler to control attributes and operations
org.springframework.jmx.export.annotation.AnnotationMBeanExporter to detect @ManagedResource annotations

Or use <context:mbean-export server="mbeanServer" default-domain="bean" />

5.4.3 Using Spring JMX, is it possible to automatically register an existing MBean with an MBeanServer?

Yes, just register them as a bean in the XML config and Spring will notice they are already MBeans. (i.e those beans implementing classes that end in MBean)

5.4.4 How to declare an MBeanServer (Jeanne)

Export MBeans:  <context:mbean-export />
Automatic registration of existing MBeans: <bean id="mine" class="ExistingMBean" />
Define MBeanServer: <context:mbean-server />

Or declare the MBeanServerFactoryBean with the locateExistingServerIfPossible property so it can use an existing server or create a new one.

5.4.5 Controlling the management interface of your beans

Exporting beans by method names, interfaces, and annotations
MBeanExporter delegates to an implementation of the org.springframework.jmx.export.assembler.MBeanInfoAssembler

  • MethodNameBasedMBeanInfoAssembler and set property "managedMethods"
  • InterfaceBasedMBeanInfoAssembler and set property "managedInterfaces"
  • MetadataMBeanInfoAssembler (with scanning turned on by <context:mbean-export />) and set property "attributeSource" (JDK (default) or Apache Commons)

Annotate class with:

  • @ManagedResource(objectName="mine") - identifies class as MBean
  • @ManagedAttribute – expose field to JMX – place on getter and setter
  • @ManagedOperation – expose method to JMX

5.4.6 Accessing remote MBean (through a proxy)


XML Schema-based Configuration Reference 

1. Util 




Instantiate a collection (list, set, map)







Instantiate a properties file






Inject a constant (static field) value 



2. J2EE     


    >> JNDI lookup




JNDI lookup




3. JMS





Top level container. 







Listen for JMS messages. Required: destination, ref




4. AOP





Enables @AspectJ support







Inject an HTTP request scoped bean into a singleton bean 







Configures aspects (alternative to annotations) for Spring AOP






Declare aspect. Pointcut can be defined inside this tag.







Declare advice (before, after, after-returning, after-throwing, around). Pointcust can be specified (with pointcut attribute) or referenced (withpointcut-ref attribute)







The concept of "advisors" is brought forward from the AOP support defined in Spring 1.2 and does not have a direct equivalent in AspectJ. An advisor is like a small self-contained aspect that has a single piece of advice.



5. Context




Automatically detect stereotyped classes and register corresponding BeanDefinitions with the ApplicationContext. AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are both included implicitly (turns on <context:annotation-config />).
Default components include: @Component (general), @Controller (web), @Repository (dao) and @Service (service)







Activates the Spring infrastructure for various annotations to be detected in bean classes. Spring's @Required and @Autowired, as well as JSR 250's @PostConstruct, @PreDestroy and @Resource (if available), and JPA's @PersistenceContext and @PersistenceUnit (if available). NOTE: This element does not activate processing of Spring's @Transactional annotation.








Activates the replacement of ${...} placeholders, resolved against the specified properties file.







Export mbeans (JMX) if you are using annotations.







Declare an MBeanServer




6. Properties





Shorthand to specify a property




7. Transaction




Define a transaction manager







Alternative to use the annotation-based approach (@Transactional) to declaring transaction configuration.







Annotation-based approach (@Transactional) to declaring transaction configuration.




8. MVC





Enable mvc annotation-based configuration. This tag registers the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter beans that are required for Spring MVC to dispatch requests to @Controllers. Note: <context:component-scan /> is also needed.




9. Security





This encapsulates the security configuration for the web layer of your application. It creates a FilterChainProxy bean named "springSecurityFilterChain" which maintains the stack of security filters which make up the web security configuration.







This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled.







This element is the primary means of adding support for securing methods on Spring Security beans.
Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax.