spring certification notes
Post on 07-Apr-2018
236 Views
Preview:
TRANSCRIPT
-
8/3/2019 Spring Certification Notes
1/40
OverviewThe following notes are very, very heavily based onJeanne Boyarsky's excellent Spring 3 Certification StudyNotes(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 onhigh level features / concepts (i.e. what can and can't feature X do, can this be applied to private methods, etc) thandetailed syntax and implementation. Topics with "(Jeanne)" were added by Jeanne and ones with (Gavin) were added byme. As Jeanne indicated, most of these are not required for the certification. However, I added these topics before I didthe exam and have not reviewed them after the exam, so please take it as a guide (and study more material rather thanless!!).
Breakdown (as perJeanne 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 awork derived from the Spring Reference Documentation (seeNotice.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
http://www.javaranch.com/jeanne/Spring_3_Certification_Study_Notes.pdfhttp://www.javaranch.com/jeanne/Spring_3_Certification_Study_Notes.pdfhttp://www.javaranch.com/jeanne/Spring_3_Certification_Study_Notes.pdfhttp://www.javaranch.com/jeanne/Spring_3_Certification_Study_Notes.pdfhttp://www.selikoff.net/2010/08/20/jeannes-core-spring-3-certification-experiences/http://www.selikoff.net/2010/08/20/jeannes-core-spring-3-certification-experiences/http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/pdf/spring-framework-reference.pdfhttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/pdf/spring-framework-reference.pdfhttp://static.springsource.org/spring/docs/3.0.x/javadoc-api/http://static.springsource.org/spring/docs/3.0.x/changelog.txthttp://springcert.sourceforge.net/licenses/spring-notice.txthttp://springcert.sourceforge.net/licenses/spring-notice.txthttp://springcert.sourceforge.net/licenses/spring-license.txthttp://www.javaranch.com/jeanne/Spring_3_Certification_Study_Notes.pdfhttp://www.javaranch.com/jeanne/Spring_3_Certification_Study_Notes.pdfhttp://www.selikoff.net/2010/08/20/jeannes-core-spring-3-certification-experiences/http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/pdf/spring-framework-reference.pdfhttp://static.springsource.org/spring/docs/3.0.x/javadoc-api/http://static.springsource.org/spring/docs/3.0.x/changelog.txthttp://springcert.sourceforge.net/licenses/spring-notice.txthttp://springcert.sourceforge.net/licenses/spring-license.txt -
8/3/2019 Spring Certification Notes
2/40
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
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 "lazy-init" on the "bean" element
Use the "default-lazy-init" on the "beans" element
Lifecycle1) 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 bean4) Set properties5) BeanPostProcessors (#postProcessBeforeInitialization)6) @PostConstruct7) InitializingBean (#afterPropertiesSet)8) Call init-method9) BeanPostProcessors (#postProcessAfterInitialization)...10) @PreDestroy
-
8/3/2019 Spring Certification Notes
3/40
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 startupprocess?
BeanFactoryPostProcessors
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.BeanPostProcessors
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
Looks for @Component (general), @Controller (web), @Repository (dao) and @Service (service)
Can set context:include-filter and context:exclude-filter elementsTurns on
Example:
1
2
3
4
1.3.2 Behavior of the annotation @Autowired with regards to field injection, constructor injection and methodinjection
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.
-
8/3/2019 Spring Certification Notes
4/40
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 for (Spring's @Required and @Autowired, JSR 250's @PostConstruct, @PreDestroyand @Resource, PA's @PersistenceContext and @PersistenceUnit)
Or 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}")
-
8/3/2019 Spring Certification Notes
5/40
1.4 Miscellaneous
1.4.1 How to inject scalar/literal values into Spring beans?
Value
Element: b@b.com
Attribute:
p namespace:
Empty:
Null:
Compound property names: person.address.streetNo
1.4.2 How to refer to a collection in a Spring bean definition?
List
1
2
3
Set
1
2
3
Properties
1
2
3
Map
1
2
3
or
1
2
-
8/3/2019 Spring Certification Notes
6/40
3
4 a
5
6 b
7 8
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 or need to specify list/set/map type, use util namespace (i.e. util:list)
Example
1
2
3
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?
1ApplicationContext ctx
= newClasspathXmlApplicationContext("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 newClasspathXmlApplicationContext("/com/mine/app-config.xml");
1.4.6 The different implementations of ApplicationContext that can be used in an application
ClasspathXmlApplicationContext
Defaults to classpath:
Starts looking from root of classpath regardless of whether specify "/"
FileSystemXmlApplicationContext
-
8/3/2019 Spring Certification Notes
7/40
Defaults to file:
Uses relative path even if specify "/", but "file:/mine" forces an absolute path
XmlWebApplicationContext
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
1
2
3
1.4.8 Purpose and usage of bean definition inheritance
Extract common bean setup into one "super" bean to reduce duplicate setup code
1
2
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
1.4.10 Difference between "id" and "name" attributes in the tag
Identifiers (id and/or name) must be unique within the container that hosts the bean.
Id
Must be unique
Limits the characters that are legal
Name
Can specify multiple names separated by comma, semicolon or space
Allows more characters in name such as slashes
-
8/3/2019 Spring Certification Notes
8/40
You are not required to supply a name or id for a bean. If no name or id is supplied explicitly, the container generates aunique 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 tag
If need to inject a bean with request/session scope into a bean with singleton scope, the proxy intercepts it and makessure you get the right bean for each call.
1
2
3
4
5
6
7
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 theampersand symbol
Example
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 getBean(Class 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 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)
-
8/3/2019 Spring Certification Notes
9/40
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)
1.4.17 Spring EL (Jeanne)
#{systemProperties.name}
1.4.18 References to other beans (collaborators) (Gavin)
Use the "bean", "local" or the "parent" attribute to control lookup context
Inner beans
A element inside the or 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
initMethod (redundant because can call method)
destroyMethod
name (aliases)
autowire (defaults to no)
@Configuration
Declares a class to be a Java based configuration
Must have default constructor
@Scope("prototype")
Used if want to change scope
@Primary
-
8/3/2019 Spring Certification Notes
10/40
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.
-
8/3/2019 Spring Certification Notes
11/40
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 beinjected. 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 pointcutexamples in the slides (apart from the ones in the "advanced topics" section at the end of themodule).
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..
Declaration:
@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
-
8/3/2019 Spring Certification Notes
12/40
Example of ref: @Before("x.y.myOperation()") where @Pointcut("within(x.y.*)") private void myOperation(){}
Example of in-place: @Before("within(x.y.*)")
@Before
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 after-
returning advice.
Use:
1 @AfterReturning(pointcut="...", returning="retval")
2 publicvoiddoAdvice(Object retVal)@AfterThrowing
After on failure only
Can change exception type thrown
Use:
1 @AfterThrowing(pointcut="...", throwing="ex")
2 publicvoiddoAdvice(Exception ex)@Around
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:
1 @Before("... && args(account,..))")
2 publicdoAdvice(Account account)
2.4 Configuration
2.4.1 Enabling the detection of @Aspect annotated classes.
2.4.2 Is it possible to set up Spring AOP using XML configuration only (as opposed to annotations)?
Yes.
-
8/3/2019 Spring Certification Notes
13/40
1
2
3
4
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 methodsLimited pointcut syntaxDoesn't get called if caller makes direct callsFinal 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: ...
3 Data Access and transactions
3.1 General
3.1.1 The rationale for having the DataAccessException hierarchy. Definition of a DataSource in the Springconfiguration
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:
If not in JNDI:
3.2 The JdbcTemplate
-
8/3/2019 Spring Certification Notes
14/40
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 classicplaceholder (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]
1 jdbc.queryFor____(String sql, Object[] args)
2jdbc.queryFor____("select count(*) from table where col > ? and col< ?", newObject[] {10, 2});
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 mapper = newRowMapper() {
2 publicA mapRow(ResultSet rs, introw) throwsSQLException {
-
8/3/2019 Spring Certification Notes
15/40
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 = newRowCallbackHandler() {
2 publicvoid processRow(ResultSet rs) {
3 }
4 };
jdbc.query(sql, handler);
3.2.6 With regard to result set parsing [merging rows into a list or other return object]
1 ResultSetExtractor extractor = new ResultSetExtractor() {
2 publicA extractData(ResultSet rs) {};
3 };
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
1BatchPreparedStatementSetter setter
= new BatchPreparedStatementSetter() {
2 publicvoid setValues(PreparedStatement stmt, introw) {}
3 publicint getBatchSize() { return0; }
4 };
with jdbcTemplate.batchUpdate(sql, setter) or pass Object[] as second parameter
3.2.10 With regard to when you need even more control
-
8/3/2019 Spring Certification Notes
16/40
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
2
3
4
5 Class1
6 Class2
7
8
9
3.3.2 Configuration of a SessionFactoryBean in xml [scanning for annotations]
1
2
3
4
5 com/mine/*
6
7
8
3.3.3 Configuration of a SessionFactoryBean in xml [listing each hbm file]
1
-
8/3/2019 Spring Certification Notes
17/40
2
3
4
5 classpath:/package/hbm.xml
6
7
8
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
2
3
HibernateTransactionManager supports Hibernate and JDBC
JdbcTransactionManager only supports JDBC
3.4.2 Configuration to declare a JTA transaction manager
3.4.3 Declarative transaction management with Spring [creating the transaction manager]
If server provides JTA:
Otherwise:
1
3
4
3.4.4 Declarative transaction management with Spring (xml)
01
02
-
8/3/2019 Spring Certification Notes
18/40
03
04
05
06
07
08
09
10
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.
to enable annotation scanning
3.4.6 Usage of TransactionTemplate for programmatic transaction management (you simply need to understand abasic example based on the TransactionTemplate).
Takes transaction manager in constructor.
Passes TransactionStatus to TransactionCallback which lets you call status.setRollbackOnly()
Example
1 publicObject someServiceMethod() {
2return transactionTemplate.execute(newTransactionCallback() {
3 publicObject doInTransaction(TransactionStatus status) {
4 updateOperation1();
5 return resultOfUpdateOperation2();
6 }
7 });
8 }
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 orrollbackForClassname/noRollbackForClassname when passing Strings
3.4.9 The @Transactional annotation: what are the main attributes that can be used for a transaction definition?
-
8/3/2019 Spring Certification Notes
19/40
timeout specified in secondsreadOnly true or falseisolation Isolation.READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ or SERIALIZABLEpropagation Propagation.REQUIRES_NEW, REQUIRED, etcrollbackFor list of exceptionsnoRollbackFor 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 andPROPAGATION_REQUIRES_NEW
REQUIRED (default)
If theres 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.
REQUIRES_NEW
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 andREAD_UNCOMMITTED?
The problem..
Dirty read:T1 ReadT2 UpdateT1 Read will be temporary and invalid.T2 Rollback
Nonrepeatable read:T1 Read
-
8/3/2019 Spring Certification Notes
20/40
T2 UpdateT1 Read value will be different
Phantom read:T1 ReadT2 InsertT1 Read will contain additional rows.
Lost updates:T1 ReadT2 ReadT1 UpdateT2 Update based on invalid Read state
The options...DEFAULTUses the default isolation level of the underlying database.For most databases, the default isolation level is READ_COMMITTED.
READ_UNCOMMITTEDAllows a transaction to read uncommitted changes by other transactions.The dirty read, nonrepeatable read, and phantom read problems may occur.
READ_COMMITTEDAllows 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_READEnsures 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.
SERIALIZABLEEnsures 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. Youwon't be asked any question on how to configure those classes. However, you need to know what thegoal of each of those components is.
View Resolver: Maps returned view name to view implementation. All handler methods in the Spring Web MVCcontrollers 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
-
8/3/2019 Spring Certification Notes
21/40
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 @RequestMappingannotation defined in the @Controller. Can be overriden (in xml) if required
Dispatcher Servlet: Front controller delegating to web infrastructure beans (handler mappings, view resolvers, typeconverters) and calling controllers/views
DispatchServlet(Request)Handler Mapping(Request) returns ControllerController(Request) returns ModelAndViewView Resolver(View Name) returns ViewView(Model) returns Responsereturns Response
4.1.2 You also need to understand the relationship between a DispatcherServlet ApplicationContext and a rootApplicationContext.
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)
- Registers the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapterbeans that are required for Spring MVC to dispatch requests to @Controllers.
- 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
2org.springframework.web.context.ContextLoaderListener
3
Loads from: /WEB-INF/applicationContext.xml
To load a specific file, use:
-
8/3/2019 Spring Certification Notes
22/40
1
2 contextConfigLocation
3 /WEB-INF/court-service.xml
4
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 keybecause it tells Spring the method can handle requests.
1 @RequestMapping("/appointments")2 publicclass AppointmentsController {...
3 @RequestMapping(value="/new", method = RequestMethod.GET)
4 public AppointmentForm getNewForm() {...}
5 }
Maps "/appointments/new" to getNewForm()
URI Template
1 @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
2 publicString findOwner(@PathVariable("ownerId") String ownerId, Modelmodel) {
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="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 aprefix/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, HttpServletResponseStream: InputStream, Reader, OutputStream, WriterAnnotated: @PathVariable, @RequestParam, @RequestHeader, @RequestBodyModel: Map, Model, ModelMapCommand or Form objects
-
8/3/2019 Spring Certification Notes
23/40
ErrorsSessionStatus
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, ViewString (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,
4.2.9 Does Spring handle Multipart request? (Gavin)
YesIf 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 elementsin 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 @PathVariableid 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?
ExampleString result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class,"42", "21");
RestTemplate t = new RestTemplate();t.getForObject(uri, MyResponse.class, id);
-
8/3/2019 Spring Certification Notes
24/40
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 methodsIf 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 HTTPrequests and from HTTP responses by HttpMessageConverters.Concrete implementations for the main media (mime) types are provided in the framework and are registered by defaultwith the RestTemplate on the client-side and with AnnotationMethodHandlerAdapter on the server-side.
Use @RequestBody to map paramUse @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/complexitySupport multiple protocolsSimplify things when both ends of remote call run Spring
5.1.2 Goal of the RMI Service Exporter
Handle server side of RMI interactionBind to registryExpose endpoint (used for everything except EJB; EJB already has mechanism to export remote)
5.1.3 General configuration of the RMI Service Exporter
and set properties:
serviceName (name in registry)
serviceInterface (interface classname)
service (reference to POJO implementing serviceInterface)
Example
-
8/3/2019 Spring Certification Notes
25/40
1
2
3
4
5
5.1.4 Goal of RMI Proxy Generator
Handle client side of RMI interactionCommunicate with endpointConvert remote exception to runtime exceptionCan treat remote EJBs as POJOs
5.1.5 General configuration of RMI Proxy Generator
-
8/3/2019 Spring Certification Notes
26/40
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
2 springSecurityFilterChain
3org.springframework.web.filter.DelegatingFilterProxy
4
5.2.4 Syntax to configure Spring Security to intercept particular URLs? (you need to have a good understandingof the various examples using intercept-url in the course)
1
2
3
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
-
8/3/2019 Spring Certification Notes
27/40
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)
and use @Secured("role1") to pass allowed roles
or and use @RolesAllowed("role1") to pass allowedroles
or without annotations:
1
2
3
or secure a bean with a list of method names using
1
2
3
4
5
5.2.6 Possible mechanisms to store user details: database? LDAP? Others?
Example
1
2
3
4
5
6
7 8
Other user servicesDatabase: In memory: 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.
-
8/3/2019 Spring Certification Notes
28/40
5.2.8 In the security tag library, what is the purpose of the tag?
To say what roles are permitted access to a section of the JSP.do stuffset propeties: i fAnyGranted, ifAllGranted
5.2.9 What does auto-config Include? (Gavin)
Shorthand for
1
2
3
4
5
Use and set properties: login-pages, default-target-url, authentication-failure-url
Use and set properties: logout-success-url
Use to setup the anon user
Use 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 theMessageConverter bean (set on the JmsTemplate) to convert the message.
MessageCreator - if need to map object to/from Message for nonstandard type
Use...
-
8/3/2019 Spring Certification Notes
29/40
1 jmsTemplate.send(this.queue, newMessageCreator() {
2 public Message createMessage(Session session) throwsJMSException {
3 return session.createTextMessage("hello queue world");
4 }
5 });
6
MessagePostProcessor interface gives you access to the message after it has been convertedUse...
1 jmsTemplate.convertAndSend("testQueue", map, new MessagePostProcessor(){
2public Message postProcessMessage(Message
message) throwsJMSException {
3 message.setIntProperty("AccountID", 1234);
4 message.setJMSCorrelationID("123-00001");
5 return message;
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() i f 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 theMessageListenerAdapter class
MessageListenerAdapterSet delegate, defaultListenerMethod properties
-
8/3/2019 Spring Certification Notes
30/40
POJO "defaultListenerMethod" method must accept one of the following types as its sole method argument: Message,String, Map, byte[], Serializable
1
2
3
4
5
Define a container
1
2
3
Extend JmsGatewaySupport
listener-containers:
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:
1
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 orJetty)?
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
Can wrap with CachingConnectionFactory if need caching
5.4 JMX
-
8/3/2019 Spring Certification Notes
31/40
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 JMXMBeanServer.
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
2
3
4
5
6
7
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 methodsas MBean operations.Use an MBeanInfoAssembler to control attributes and operationsorg.springframework.jmx.export.annotation.AnnotationMBeanExporter to detect @ManagedResource annotations
Or use
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 beansimplementing classes that end in MBean)
5.4.4 How to declare an MBeanServer (Jeanne)
Export MBeans: Automatic registration of existing MBeans: Define MBeanServer:
Or declare the MBeanServerFactoryBean with the locateExistingServerIfPossible property so it can use an existing serveror create a new one.
5.4.5 Controlling the management interface of your beans
Exporting beans by method names, interfaces, and annotationsMBeanExporter 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 ) 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
-
8/3/2019 Spring Certification Notes
32/40
@ManagedOperation expose method to JMX
5.4.6 Accessing remote MBean (through a proxy)
1
-
8/3/2019 Spring Certification Notes
33/40
Example 1
2. J2EE
>> JNDI lookup
Name jndi-lookup
Description JNDI lookup
Example1
3. JMS
Namelistener-container
Description
Top level container.
Example1
2
3
Name listener
Description
Listen for JMS messages. Required: destination, ref
-
8/3/2019 Spring Certification Notes
34/40
Example1
4. AOP
Nameaspectj-autoproxy
Description Enables @AspectJ support
Example 1
Namescoped-proxy
Description
Inject an HTTP request scoped bean into a singleton bean
Example1
2
3
Name config
Description
Configures aspects (alternative to annotations) for Spring AOP
Example 1
2
3
4
-
8/3/2019 Spring Certification Notes
35/40
>
5
6
Name aspect
Description Declare aspect. Pointcut can be defined inside this tag.
Example 1
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
Name advice
Description The concept of "advisors" is brought forward from the AOP support definedin Spring 1.2 and does not have a direct equivalent in AspectJ. An advisor islike a small self-contained aspect that has a single piece of advice.
Example 1
2
3
4
5
6
7
-
8/3/2019 Spring Certification Notes
36/40
8
9
5. Context
Name component-scan
Description
Automatically detect stereotyped classes and register correspondingBeanDefinitions with the ApplicationContext.AutowiredAnnotationBeanPostProcessor andCommonAnnotationBeanPostProcessor are both included implicitly (turns on).Default components include: @Component (general), @Controller (web),@Repository (dao) and @Service (service)
Example
1
2
3
4
Name annotation-config
Description Activates the Spring infrastructure for various annotations to be detected inbean 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: Thiselement does not activate processing of Spring's @Transactional annotation.
Example 1
Nameproperty-placeholder
-
8/3/2019 Spring Certification Notes
37/40
Description Activates the replacement of ${...} placeholders, resolved against thespecified properties file.
Example1
Name mbean-export
Description Export mbeans (JMX) if you are using annotations.
Example1
Name mbean-server
Description Declare an MBeanServer
Example 1
6. Properties
Name p-name
Description Shorthand to specify a property
Example 1 2
7. Transaction
Name jta-transaction-manager
-
8/3/2019 Spring Certification Notes
38/40
Description Define a transaction manager
Example 1
Nameadvice
Description Alternative to use the annotation-based approach (@Transactional) todeclaring transaction configuration.
Example 1
2
3
4
5
6
Nameannotation-driven
Description Annotation-based approach (@Transactional) to declaring transactionconfiguration.
Example 1
8. MVC
Nameannotation-driven
-
8/3/2019 Spring Certification Notes
39/40
Description Enable mvc annotation-based configuration. This tag registers theDefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapterbeans that are required for Spring MVC to dispatch requests to @Controllers.Note: is also needed.
Example 1
9. Security
Name http
Description
This encapsulates the security configuration for the web layer of yourapplication. It creates a FilterChainProxy bean named"springSecurityFilterChain" which maintains the stack of security filterswhich make up the web security configuration.
Example 1
2
3
Nameintercept-url
Description
This element is used to define the set of URL patterns that the application isinterested in and to configure how they should be handled.
Example1
Nameglobal-method-security
Description This element is the primary means of adding support for securing methods on
-
8/3/2019 Spring Certification Notes
40/40
Spring Security beans.Methods can be secured by the use of annotations (defined at the interface orclass level) or by defining a set of pointcuts as child elements, using AspectJsyntax.
Example1
2
3
4
5
67
top related