You are on page 1of 40

Overview

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

Reference Manual ( HTML / PDF ) API (Javadoc) Change Log

License
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? Pros

Loosely coupled code

Autowire Dependency checking

1.1.2 Dependency injection in XML, using constructor <constructor-arg/> 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 <property/> 1.1.4 Scopes Supported

Singleton (default) Prototype Web (session, request)

1.2 Lifecycle
1.2.1 How to declare an initialization method in a Spring bean [in XML]? init-method 1.2.2 How to declare a destroy method in a Spring bean [in XML]? destroy-method 1.2.3 Default bean instantiation policy: when are beans instantiated? For Singleton, when app context is created / parsed To specify instantiation policy

Use the "default-lazy-init" on the "beans" element Lifecycle 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

Use "lazy-init" on the "bean" element

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? BeanFactoryPostProcessors

If BeanFactoryPostProcessors are marked as being lazily-initialized they will NOT be instantiated and will NOT apply their logic. BeanPostProcessors

Each processor is called once per xml (i.e per application context) Before beans are instantiated Can change bean configuration / definitions

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 /> Example:

1 <context:component-scan base-package="org.example"> 2 3 4 "/> <context:include-filter type="regex" expression=".*Stub.*Repository

<context:exclude-filter type="annotation" expression="org.springfram ework.stereotype.Repository"/> </context:component-scan>

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

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? @Qualifier(name) 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) Used

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? Value

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? List

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

1 <list> 2 <ref bean="one" /> 3 </list>


Set

1 <set> 2 <ref bean="one" /> 3 </set>


Properties

1 <props> 2 <prop key="a" value="b" /> 3 </props>


Map

1 <map> 2 <entry key="a" value="b" /> 3 </map>


or

1 <map> 2 <entry>

3 4 5 6 7 8 </map>

<key> <value>a</value> </key> <value>b</value> </entry>

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) Example

1 <util:list id="beanList" list-class="java.util.LinkedList"> 2 <ref bean="one" /> 3 </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?

ApplicationContext ctx = new ClasspathXmlApplicationContext("one.ctx","two.ctx");


Supports multiple resources 1.4.4 What are the resource prefixes that can be used? classpath: file: http: 1.4.5 How to refer to a Spring configuration file inside a package?

1 new ClasspathXmlApplicationContext("/com/mine/app-config.xml");

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

Starts looking from root of classpath regardless of whether specify "/" FileSystemXmlApplicationContext

Defaults to classpath:

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

Defaults to file:

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 <context:property-placeholder location="/myFile.properties" />

1 <bean id="mind" class="Mine"> 2 <property name="a" value="${myProperty}" /> 3 </bean>

1.4.8 Purpose and usage of bean definition inheritance Extract common bean setup into one "super" bean to reduce duplicate setup code

1 <bean id="parentBean" class="MyClass" abstract="true" /> 2 <bean id="child" parent="parentBean" class="MyDerivedClass"/>


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 <bean id="a" class="MyClass" 2 3 p:propName1="value" p:propName2-ref="otherBean"/>

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. Id

Name

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 <bean id="userPref" scope="session"> 2 4 5 <bean ...> 6 <property ref="userPref"/> 7 </bean>


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 Example

<scoped-proxy/>

3 </bean>

Invoking getBean("&myBean") returns the FactoryBean instance itself To get a bean programatically from the ApplicationContext:

Invoking getBean("myBean") on the container returns the product of the FactoryBean

<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) #{systemProperties.name} 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 @Bean Declared on a method that creates a bean in a Java based configuration. Takes properties

autowire (defaults to no) @Configuration

initMethod (redundant because can call method) destroyMethod name (aliases)

Declares a class to be a Java based configuration

Must have default constructor @Scope("prototype") Used if want to change scope

@Primary

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:

@target, @args, @within, @annotation .. has annotation of.. Declaration:

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

@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

@Before

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

After unconditionally Handles normal and exception return

Can change return value or throw an exception @AfterReturning After on success only

Can change return value but it is not possible to return a totally different reference when using afterreturning advice. Use:

1 @AfterReturning(pointcut="...", returning="retval") 2 public void doAdvice(Object retVal)


@AfterThrowing

After on failure only Can change exception type thrown Use:

1 @AfterThrowing(pointcut="...", throwing="ex") 2 public void doAdvice(Exception ex)


@Around

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:

Surrounds Takes ProceedingJoinPoint, can intercept call or ignore exception First parameter of the advice method must be of type ProceedingJoinPoint

1 @Before("... && args(account,..))") 2 public doAdvice(Account account)


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)? Yes.

1 <aop:config> 2 3 <aop:aspect ref="adviceBean"> <aop:before pointcut="execution...." />

4 </aop:config>

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. Example

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...

Clearer names easy to catch and handle specific errors Datasource definition

Runtime exception doesn't force developers to catch and rethrow Consistent/non-vendor specific messages isolates from database

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.

Note: As of Spring 3, JdbcTemplate uses JDK 1.5 features such as var-args Spring and you

getJdbcOperations, getNamedParameterJdbcOperations to get underlying template

(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]

1 jdbc.queryFor____(String sql, Object[] args) 2 jdbc.queryFor____("select count(*) from table where < ?", newObject[] {10, 2}); col > ? and col

3 jdbc.queryFor____(String sql, Object... args)


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]

1 RowMapper<A> mapper = new RowMapper<A>() { 2 public A mapRow(ResultSet rs, int row) throws SQLException {

3 4 };

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]

1 RowCallbackHandler handler = new RowCallbackHandler() { 2 3 4 };


jdbc.query(sql, handler); 3.2.6 With regard to result set parsing [merging rows into a list or other return object]

public void processRow(ResultSet rs) { }

1 ResultSetExtractor<A> extractor = new ResultSetExtractor<A>() { 2 3 public A };


jdbc.query(sql, extractor); 3.2.7 With regard to querying [for insert/update/delete row] jdbc.update(sql); jdbc.update(PreparedStatementCreator, KeyHolder) 3.2.8 With regard to running DDL jdbc.execute(sql); 3.2.9 With regard to batch updates

extractData(ResultSet rs) {};

1 2 3

BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() { public void setValues(PreparedStatement stmt, int row) {} public int getBatchSize() { return 0; }

4 };
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").

1 <bean id="sf" class="os.orm.hibernate3.annotation.AnnotationSessionFacto ryBean"> 2 3 4 5 6 7 8 9 </bean> <property name="dataSource" ref="d" /> <property name="annotatedClasses"> <list> <value>Class1</value> <value>Class2</value> </list> </property>

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

1 <bean id="sf" class="os.orm.hibernate3.annotation.AnnotationSessionFacto ryBean"> 2 3 4 5 6 7 8 </bean> <property name="dataSource" ref="d" /> <property name="packagesToScan"> <list> <value>com/mine/*</value> </list> </property>

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

1 <bean id="sf" class="os.orm.hibernate3.LocalSessionFactoryBean">

2 3 4 5 6 7

<property name="dataSource" ref="d" /> <property name="mappingLocations"> <list> <value>classpath:/package/hbm.xml</value> </list> </property>

8 </bean>

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

1 <bean id="mgr"class="org.springframework.jdbc.datasource.DataSourceTrans actionManager"> 2 <property name="dataSource" ref="dataSource"/> 3 </bean>


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 /> Otherwise:

1 2 3

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactio nManager"> <property name="dataSource" ref="ds" />

4 </bean>
3.4.4 Declarative transaction management with Spring (xml)

01 <aop:config> 02 <aop:advisor pointcut-ref="p" advice-ref="ta" />

03 </aop:config> 04 05 <tx:advice id="ta"> 06 07 08 09 <tx:attributes> <tx:method name="update*" timeout="60" /> <tx:method name="*" timeout="30" read-only="true" /> </tx:attributes>

10 </tx:advice>

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() Example

1 public Object 2 3 4 5 6 7 8 } }); }

someServiceMethod() {

return transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { updateOperation1(); return resultOfUpdateOperation2();

3.4.7 Transactions and exception management: what is the default rollback policy? Rollback for a RuntimeException 3.4.8 Can it be overridden? Yes. 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 isolation Isolation.READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ or SERIALIZABLE 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? Yes 3.4.11 Regarding propagation modes, what is the difference between PROPAGATION_REQUIRED and PROPAGATION_REQUIRES_NEW REQUIRED (default)

Otherwise, it should start a new transaction and run within its own transaction. REQUIRES_NEW

If theres an existing transaction in progress, the current method should run within this transaction.

The current method must start a new transaction and run within its own transaction.

If theres an existing transaction in progress, it should be suspended. SUPPORTS If theres an existing transaction in progress, the current method can run within this transaction.

Otherwise, it is not necessary to run within a transaction. NOT_SUPPORTED The current method should not run within a transaction.

If theres an existing transaction in progress, it should be suspended. MANDATORY The current method must run within a transaction. If theres no existing transaction in progress, an exception will be thrown.

NEVER

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

NESTED If theres 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... DEFAULT Uses the default isolation level of the underlying database. For most databases, the default isolation level is READ_COMMITTED. READ_UNCOMMITTED Allows a transaction to read uncommitted changes by other transactions. The dirty read, nonrepeatable read, and phantom read problems may occur. READ_COMMITTED 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. REPEATABLE_READ 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. SERIALIZABLE 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 DispatchServlet(Request) 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) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) 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.

1 <listener> <listener2 class>org.springframework.web.context.ContextLoaderListener</listenerclass> 3 </listener>


Loads from: /WEB-INF/applicationContext.xml To load a specific file, use:

1 <context-param> 2 3 <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/court-service.xml</param-value>

4 </context-param>
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.

1 @RequestMapping("/appointments") 2 public class AppointmentsController {... 3 4 5 }


Maps "/appointments/new" to getNewForm() URI Template

@RequestMapping(value="/new", method =

RequestMethod.GET)

public AppointmentForm getNewForm() {...}

1 @RequestMapping(value="/owners/{ownerId}",

method=RequestMethod.GET) String ownerId, Model

2 public String findOwner(@PathVariable("ownerId") model) {


Advanced

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="contenttype=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

Errors SessionStatus 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) Yes 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? Example 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); t.delete(uri); 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:

Example

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

1 <bean class="org.springframework.remoting.rmi.RmiServiceExporter"> 2 3 4 <property name="serviceName" value="AccountService"/> <property name="service" ref="accountService"/> <property name="serviceInterface" value="example.AccountService"/>

5 </bean>

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:

Example

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

1 <bean id="accountService" class="org.springframework.remoting.rmi.RmiPro xyFactoryBean"> 2 3 /> <property name="serviceUrl" value="rmi://HOST:1199/AccountService" <property name="serviceInterface" value="example.AccountService"/>

4 </bean>
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. XML over HTTP 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:

1 <filter> 2 <filter-name>springSecurityFilterChain</filter-name> <filter3 class>org.springframework.web.filter.DelegatingFilterProxy</filterclass> 4 </filter>


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)

1 <security:http> 2 <security:intercept-url pattern="/stuff/**" [method="GET"] access=" role1, role2" />

3 </security:http>
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:

1 <security:global-method-security> 2 <security:protect-pointcut expression="execution(* doStuff())" access="role"/>


or secure a bean with a list of method names using

3 </security:global-method-security>

1 <bean id="..." > 2 3 4 <security:intercept-methods> <security:protect method="com.apress.springrecipes.board.service .MessageBoardService.listMessages" access="ROLE_USER,ROLE_GUEST" /> </security:intercept-methods>

5 </bean>
5.2.6 Possible mechanisms to store user details: database? LDAP? Others? Example

1 <authentication-manager> 2 3 4 5 6 7 <authentication-provider> <user-service> <user name="jimi" password="jimispassword" authorities="ROL E_USER, ROLE_ADMIN" /> <user name="bob" password="bobspassword" authorities="ROLE_ USER" /> </user-service> </authentication-provider>
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" />

8 </authentication-manager>

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

1 <http> 2 3 4 <form-login /> <http-basic /> <logout />


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 </http>

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

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 Use...

SingleConnectionFactory

1 jmsTemplate.send(this.queue, new MessageCreator() { 2 3 4 5 }); 6


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

public Message createMessage(Session session) throws JMSException { return session.createTextMessage("hello queue world"); }

1 jmsTemplate.convertAndSend("testQueue", map, new MessagePostProcessor() { 2 3 4 5 6 7 });


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

public Message postProcessMessage(Message message) throws JMSException { message.setIntProperty("AccountID", 1234); message.setJMSCorrelationID("123-00001"); return message; }

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 MessageListenerAdapter Set delegate, defaultListenerMethod properties

template.receive() take optional destination

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

1 <bean id="messageListener" class="org.springframework.jms.listener.adapt er.MessageListenerAdapter"> 2 3 4 5 </bean> <constructor-arg> <bean class="MyDelegate"/> </constructor-arg>

Define a container

1 <jms:listener-container connection-factory="connFactoryRef"> 2 <jms:listener destination="d" ref="myDelegate" />


Extend JmsGatewaySupport listener-containers:

3 </jms:listener-container>

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:

<jms:listener destination="d" ref="myDelegate" method="m" responsedestination="rd" />


Where

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)? Yes. 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

1 <bean class="org.springframework.jmx.export.MBeanExporter"> 2 3 4 5 6 7 </bean>


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

<property name="beans"> <util:map> <entry key="bean:name=mine" value-ref="beanRef" /> </util:map> </property>

MetadataMBeanInfoAssembler (with scanning turned on by <context:mbean-export />) and set property "attributeSource" (JDK (default) or Apache Commons) Annotate class with:

MethodNameBasedMBeanInfoAssembler and set property "managedMethods" InterfaceBasedMBeanInfoAssembler and set property "managedInterfaces"

@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)

1 2 3 4 5 6

<bean id="mbeanServerConnection"...

</bean>

<bean id="..." class="org.springframework.jmx.access.MBeanProxyFact oryBean"> <property name="server" ref="mbeanServerConnection" /> <property name="objectName" value="bean:name=mine" /> <property name="proxyInterface" value="Mine" /> </bean>

7 </beans>

XML Schema-based Configuration Reference


1. Util

Name

list

Description Instantiate a collection (list, set, map) Example

1 <util:list id="beanList" listclass="java.util.LinkedList"> 2 <ref bean="one" /> 3 </util:list>

Name

properties

Description Instantiate a properties file Example


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

Name

constant

Description Inject a constant (static field) value

Example

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

2. J2EE

>> JNDI lookup

Name

jndi-lookup

Description JNDI lookup Example

1 <jee:jndi-lookup id="ds" jndi-name="java:comp/env/jdbc/DS" />

3. JMS

listener-container Name Descriptio Top level container. n Example

1 <jms:listener-container connectionfactory="connFactoryRef"> 2 /> <jms:listener destination="dest" ref="listenerBeanRef"

3 </jms:listener-container>

Name

listener

Descriptio Listen for JMS messages. Required: destination, ref n

Example

<jms:listener ref="pojo" method="m" destination="dest" respo nse-destination="rd" />

4. AOP

aspectj-autoproxy Name Description Enables @AspectJ support Example


1 <aop:aspectj-autoproxy />

scoped-proxy Name Descripti Inject an HTTP request scoped bean into a singleton bean on Example

1 <bean id="userPreferences" class="com.foo.UserPreferences"sc ope="session"> 2 <aop:scoped-proxy/> 3 </bean>

Name

config

Descriptio Configures aspects (alternative to annotations) for Spring AOP n Example


1 <aop:config> 2 3 4 <aop:aspect ref="adviceBean"> <aop:pointcut id="businessService" expression="executio n(* com.xyz.myapp.service.*.*(..))"/> <aop:before pointcut="execution...." method="monitor"/

> 5 <aop:advisor pointcut-ref="p" advice-ref="ta" /> 6 </aop:config>

Name

aspect

Description Declare aspect. Pointcut can be defined inside this tag. Example
1 <aop:aspect ref="adviceBean">

Name

before

Description Declare advice (before, after, after-returning, after-throwing, around). Pointcust can be specified (with pointcut attribute) or referenced (withpointcut-ref attribute) Example
1 <aop:before pointcut="execution...." method="monitor"/>

Name

advice

Description 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. Example
1 <aop:config> 2 <aop:advisor pointcut-ref="businessService" adviceref="tx-advice"/>

3 </aop:config> 4 5 <tx:advice id="tx-advice"> 6 7 <tx:attributes> <tx:method name="*" propagation="REQUIRED"/>

</tx:attributes>

9 </tx:advice> 5. Context

Name

component-scan

Descript Automatically detect stereotyped classes and register corresponding ion 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) Exampl 1 <context:component-scan base-package="org.example"> e
2 3 4

<context:include-filter type="regex"expression=".*Stub.* Repository"/>

<context:exclude-filter type="annotation"expression="org .springframework.stereotype.Repository"/> </context:component-scan>

Name

annotation-config

Description 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. Example
1 <context:annotation-config />

property-placeholder Name

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

1 <context:property-placeholder location="/myFile.propertie s"/>

Name

mbean-export

Description Export mbeans (JMX) if you are using annotations. Example

<context:mbean-export server="mbeanServer" defaultdomain="bean" />

Name

mbean-server

Description Declare an MBeanServer Example


1 <context:mbean-server />

6. Properties

Name

p-name

Description Shorthand to specify a property Example


1 <... p:propName="value" /> 2 <... p:propName-ref="otherBean" />

7. Transaction

Name

jta-transaction-manager

Description Define a transaction manager Example


1 <tx:jta-transaction-manager />

advice Name Description Alternative to use the annotation-based approach (@Transactional) to declaring transaction configuration. Example
1 <tx:advice id="ta"> 2 3 4 5 > </tx:attributes> <tx:attributes> <tx:method name="update*" timeout="60" /> <tx:method name="*" timeout="30" read-only="true" /

6 </tx:advice>

annotation-driven Name Description Annotation-based approach (@Transactional) to declaring transaction configuration. Example
1 <tx:annotation-driven />

8. MVC

annotation-driven Name

Description 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. Example
1 <mvc:annotation-driven />

9. Security

Name

http

Descriptio This encapsulates the security configuration for the web layer of your n application. It creates a FilterChainProxy bean named "springSecurityFilterChain" which maintains the stack of security filters which make up the web security configuration. Example
1 <security:http> 2 <security:intercept-url pattern="/stuff/**" [method="GE T"]access="role1,role2" />

3 </security:http>

intercept-url Name Descripti This element is used to define the set of URL patterns that the application is on interested in and to configure how they should be handled. Example

<security:intercept-url pattern="/stuff/**" [method="GET"]ac cess="role1,role2" />

global-method-security Name Description 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. Example

1 2 3 4

<security:global-method-security securedannotations="enabled" />

<security:global-method-security jsr250annotations="enabled" />

5 <security:global-method-security> 6 <security:protect-pointcut doStuff())"access="role" /> expression="execution(*

7 </security:global-method-security>

You might also like