Spring Core 3.2 - Study Notes © 2013 Arnošt Havelka

Disclaimer

This artical is heavily based on artical Core Spring Professional Certification Study Guides, Resources, Mock Exams by Gavin Lasnitzki (and of course jeanne’s core spring 3 certification experiences by Jeanne Boyarsky). I tried to make this article closer to an exam scope. Additionally I updated notes to spring framework 3.2.x.

SpringSource Certification

Summary of certification exam defined in study guide is:

Spring Reference Docs 3.2.x


1. Container

1.1 General

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

1.1.2 Dependency injection in XML, using constructor or setter injection

Constructor

<constructor-arg/>

Only works if there is no ambiguity in args. Use the following attributes to reduce ambiguity:

C namespace - similar to P namespace

<beans ...  xmlns:c="http://www.springframework.org/schema/c">
-- by name
<bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="foo@bar.com">
-- by index
<bean id="foo" class="x.y.Foo" c:_0-ref="bar" c:_1-ref="baz">
Setter

<property/>

<bean id="exampleBean" class="examples.ExampleBean">
	<property name="value" value="my value"/> -- literal value
	<property name="service" ref="myService"/> -- refence to other bean
</bean>

P namespace

<beans ...  xmlns:p="http://www.springframework.org/schema/p">
<bean id="foo" class="x.y.Foo" p:value="my value" p:service-ref="myService"/>

1.1.3 Scopes

1.2 Lifecycle

Definition of application context 1 BFPP 2 Bean Definition 3 + 4 BPP 5 + 9 Instance 6-8 Ready
    Init:
  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 bean definition
  3. Instantiate each bean
  4. Set properties
  5. BeanPostProcessors (#postProcessBeforeInitialization)
  6. @PostConstruct
  7. InitializingBean (#afterPropertiesSet)
  8. Call init-method
  9. BeanPostProcessors (#postProcessAfterInitialization)
    Destroy:
  1. @PreDestroy
  2. DisposableBean (#destroy)
  3. Call destroy-method
BeanFactoryPostProcessors vs. BeanPostProcessors

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

1.2.2 How to declare a destroy method in a Spring bean?

1.2.3 Default bean instantiation policy: when are beans instantiated?

Mem:

1.2.x What is a FactoryBean?

Underlying basis for Spring's IoC functionality

1.3 Annotations

1.3.1 Enabling component-scanning

Example:

<context:component-scan  base-package="org.example">
    <context:include-filter type="regex"  expression=".*Stub.*Repository"/>
    <context:exclude-filter type="annotation"  expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

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

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

May be applied to:

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

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) and process all DI annotations.

1.3.6 Other

Other annotations SpEL

1.4 Miscellaneous

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

<bean ... >
	<property ...><value>b@b.com</value></property> <!-- element -->
	<property ... value="b@b.com" /> <!-- attribute -->
</bean>

<bean ...  p:email="b@b.com" /> <!-- P namespace -->

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

<list>
    <ref bean="one" />
</list>
<set>
    <ref bean="one" />
</set>
<props> <!-- properties -->
    <prop key="a" value="b" />
</props>
<map>
    <entry key="a" value="b" />
</map>

<!-- or -->

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

1.4.3 How to create an ApplicationContext? What are the resource prefixes that can be used? How to refer to a Spring configuration file inside a package? The different implementations of ApplicationContext that can be used in an application.

Creation of ApplicationContext
// XML configuration
ApplicationContext ctx = new ClasspathXmlApplicationContext("one.ctx","two.ctx");

// JavaConfig
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

Supports multiple resources

Prefixes Reference to configuration file
new ClasspathXmlApplicationContext("/com/mine/app-config.xml");
Implementations of ApplicationContext

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

context:property-placeholder

Definition/config:

<context:property-placeholder location="/myFile.properties" />

Usage in XML:

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

Usage with annotation:

@Value("${myProperty}")
private String value;
util:properties

Configuration:

<util:properties id="myProperties" location="/myFile.properties" />

Usage:

<bean id="mind" class="Mine" p:a="#{myProperties[myPropName]}"/>
@Value("#{myProperties[myPropName]}") // specify property file and configuration item
private String myField; 

@Value("#{myPropName}") // if there is only one property file
private String myField; 

1.4.5 Purpose and usage of bean definition inheritance

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

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

1.4.6 How to use the p namespace?

Set property as attributes

<beans ...  xmlns:p="http://www.springframework.org/schema/p">
<bean id="foo" class="x.y.Foo" 
	p:value="my value" <!-- literal value -->
	p:service-ref="myService"/> <!-- bean reference -->

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

<bean id="userPref" scope="session">
	<aop:scoped-proxy/>
</bean>

<bean ...>
	<property ref="userPref"/>
</bean>

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

getBean("myBean") -- returns reference of bean created by FactoryBean
getBean("&myBean") -- returns reference of the FactoryBean instance itself

1.4.10 How to inject using a factory method?

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
	<!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService"
      factory-bean="serviceLocator"
      factory-method="createClientServiceInstance"/>

1.4.11 Splitting the XML

1.4.12 Use constants in configuration

XML:

<util:constant id="maxInt" static-field="java.lang.Integer.MAX_VALUE"/>

Java:

public class Foo {
    @Value("T(java.lang.Integer).MAX_VALUE")
    private Integer myValue;
}

1.4.13 Other annotations

1.5 JavaConfig

1.5.1 Usage of the @Bean and @Configuration annotations

@Configuration

@Bean - declares a method as spring bean (in a Java based configuration). Properties are:

Other usefull annotations:

1.5.2 How to write a bean definition method?

@Bean // Defines a String bean with the id "myBean" and  the value "hi"
public String myBean() {
	return "hi";
}

1.6 Testing

Unit testing Integration testing

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

Annotations @RunWith(SpringJUnit4ClassRunner) and @ContextConfiguration provides the benefits of the TestContext framework

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/META-INF/spring/hello-app-context.xml")
public class HelloServiceDefaultTest {

	@Autowired
	private HelloService service;

	@Test
	public void testSimpleProperties() throws Exception {
		assertNotNull(service);
	}
}

Others:

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

1.6.3 Differences between a Unit test and an Integration test. Which of them is supposed to 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.

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

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

Declaration:

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

2.3 Advice

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

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.

<aop:config>
	<aop:aspect ref="adviceBean">
		<aop:before pointcut="execution...." method="foo" />
	</aop:aspect>
</aop:config>

2.5 Proxies

2.5.1 When are they generated in the Spring lifecycle? How do they resemble the target object that they advice? What limitations does Spring-AOP's proxy-based approach have?

Proxy in Spring lifecycle

They are created by Bean Post Processing.

Resemblance of proxy and target object

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

Proxy limits

3. Data Access and transactions

3.1 General

3.1.1 The rationale for having the DataAccessException hierarchy.

3.1.2 Definition of a DataSource in the Spring configuration

3.2 The JdbcTemplate

Spring and you:

MEM:

3.2.1 Usage of the JdbcTemplate with regards to exception handling

Key methods:

Examples of data querying:

// querying with parameters
jdbc.queryForXyz(String sql, Object[] args)
jdbc.queryForXyz("select count(*) from table where  col > ? and col < ?", new Object[] {10, 2}); 
jdbc.queryForXyz(String sql, Object... args) 


// usage of mapping entity
RowMapper mapper = new RowMapper() {
    public A  mapRow(ResultSet rs, int row) throws SQLException {...}
};
jdbc.query(sql, mapper); // use with query (generally for a list)
jdbc.queryForObject(sql, mapper); // load a single entity


// usage of writting out data
RowCallbackHandler handler = new RowCallbackHandler() {
    public void  processRow(ResultSet rs) {...}
};
jdbc.query(sql, handler);


// usage of mapping resultset into entity
ResultSetExtractor extractor = new  ResultSetExtractor() {
    public A extractData(ResultSet rs) {...};
};
jdbc.query(sql, extractor);

Examples of special operations:

// querying for DML (insert/update/delete row)
jdbc.update(sql);
jdbc.update(PreparedStatementCreator, KeyHolder)


// executing DDL
jdbc.execute(sql);


// executing batch update
BatchPreparedStatementSetter setter = new  BatchPreparedStatementSetter() {
    public void  setValues(PreparedStatement stmt, int row) {}
    public int  getBatchSize() { return 0; }
}
jdbcTemplate.batchUpdate(sql, setter); // or pass  Object[] as second parameter

3.3 Hibernate

3.3.1 Configuration of a SessionFactoryBean in xml

Instances:

Read only transactions prevent Hibernate from flushing session.

3.4 Transactions

3.4.1 Configuration to declare a local transaction manager

<bean id="mgr" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property  name="dataSource" ref="dataSource"/>
</bean>

3.4.2 Configuration to declare a JTA transaction manager

<bean id="mgr" class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

or

<tx:jta-transaction-manager />

3.4.3 The different ways to do declarative transaction management with Spring (xml, annotations)

We have to define transaction manager first (see previous chapters).

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

<tx:advice id="ta">
    <tx:attributes>
        <tx:method name="update*" timeout="60" />
        <tx:method name="*" timeout="30"  read-only="true" />
    </tx:attributes>
</tx:advice>
Annotations

Use annotation @Transactional as:

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

Example:

public Object  someServiceMethod() {
    return  transactionTemplate.execute(new TransactionCallback() {
        public Object  doInTransaction(TransactionStatus status) {
            try {
                updateOperation1();
            } catch (XyzException e) {
                status.setRollbackOnly();
            }
            return  resultOfUpdateOperation2();
        }
    });
}

3.4.5 Transactions and exception management: what is the default rollback policy? Can it be overridden?

3.4.6 The @Transactional annotation: what are the main attributes that can be used for a transaction definition? Can this annotation also be used with a JTA Transaction Manager?

Main attributes of @Transactional annotation: Usage with JTA transaction manager:

Yes

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

Main attributes of @Transactional annotation are:

MEM: If methodA calls methodB directly, the transaction attributes of methodB are NOT used (due to proxy issue).

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

Read phenomena:

The options to solve the read phenomena are:

4. Spring MVC

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

Some of implementations:

Handler Mapping Dispatch Servlet

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

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 ${servlet_name}-servlet.xml. We need (to configure DispatcherServlet properly) to do:

4.2.2 General usage of the @Controller and @RequestMapping annotations

Example of mapping "/appointments/new" to getNewForm() (for only GET):

@Conttroller
@RequestMapping("/appointments")                              
public class  AppointmentsController {...
    @RequestMapping(value="/new", method =  RequestMethod.GET)
    public  AppointmentForm getNewForm() {...}
}
URI Template
@RequestMapping(value="/owners/{ownerId}",  method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId")  String ownerId, Model model) {

4.2.3 A method annotated with @RequestMapping can return a String. What does it refer to? What are the main parameter types that this method can accept? (based on what you've seen in the class)

MEM: Method can not return absolute path to view.

4.2.4 Goal of the @RequestParam annotation

@RequestMapping(method=RequestMethod.GET)
public String findOwner(@RequestParam("ownerId")  String ownerId, Model model) {

4.2.5 Configuring Spring MVC via XML

<mvc:annotation-driven />
<mvc:interceptors  />

4.2.6 Does Spring handle Multipart request?

Yes

4.3 REST

4.3.1 Differences between GET, POST, PUT and DELETE

@RequestMapping defines URI to resource, action (what to do with the resource) is defined by HTTP method:

4.3.2 Usage of the @PathVariable annotation

Maps parts of the url in @RequestMapping to a parameter (marked by annotation @PathVariable). For example the URL /account/{id} goes with @PathVariable id in the method signature. See URI template in chapter 4.2.2

4.3.3 What is the RestTemplate?

Programmatic client for calling RESTful URLs.

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

4.3.4 Purpose of the @ResponseStatus Annotation

4.3.5 Purpose of the @ExceptionHandler Annotation

For example:

@ExceptionHandler({MyException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "My Response Status Change….!!")
public void handleMyException(MyException ex, HttpServletResponse response) {
	logger.info("Handlng MyException - Catching: " + ex.getClass().getSimpleName());
}

4.3.6 What are HttpMessageConverters?

5. Advanced topics

5.1 Remoting

5.1.1 Advantages of using Spring Remoting rather than plain RMI?

5.1.2 Goal and general configuration of the RMI Service Exporter

Goals: General configuration:
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
    <property name="serviceName" value="AccountService"/> <!-- name in registry -->
    <property name="service" ref="accountService"/> <!-- reference to POJO implementing  serviceInterface -->
    <property name="serviceInterface" value="example.AccountService"/> <!-- interface classname -->
    <property name="registryPort" value="1199"/> <!-- defaults to 1099 -->
</bean>

5.1.3 Goal and general configuration of RMI Proxy Generator

Goals: General configuration:
<bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
    <property name="serviceUrl" value="rmi://HOST:1199/AccountService"/> <!-- endpoint in registry (rmi://server:port/serviceName) -->
    <property name="serviceInterface" value="example.AccountService"/> <!-- interface classname -->
</bean>

5.1.4 Difference between the RMI Service Exporter and the HttpInvoker

<bean name="/AccountService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
    <property name="service" ref="accountService"/> <!-- reference to POJO implementing  serviceInterface -->
    <property name="serviceInterface" value="example.AccountService"/> <!-- interface classname -->
</bean>
<bean id="httpInvokerProxy" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
    <property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/>
    <property name="serviceInterface" value="example.AccountService"/> <!-- interface classname -->
</bean>

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

Hessian (Caucho's binary-based format), Burlap (Caucho's XML-based format), HttpInvoker (spring's binary-based format) need a web server on the server side, but not on the client side.

5.2 Security

Basic concepts:

Security is configured (activated) in web.xml as:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

Auto-config includes:

<http>
    <form-login /> <!-- to set form login authentication (login-pages, default-target-url, authentication-failure-url) -->
    <http-basic /> <!-- to set HTTP basic authentication -->
    <logout /> <!-- to set logout-success-url -->
    <anonymous username="guest"  granted-authority="ROLE_GUEST" /> <!-- to setup the anonymous user -->
    <remember-me /> <!-- to setup Remember-Me support -->
</http>

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

Series of servlet filters (declared in web.xml) that must be passed before/after resource is accessed. The chain is declared in web.xml (as servlet filter) and consists of:

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

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

5.2.3 Syntax to configure method level security

Global setting (in XML):
<security:global-method-security>
    <security:protect-pointcut expression="execution(* doStuff())" access="hasRole('ROLE_USER')" />
</security:global-method-security>
Secure a bean with a list of method names using:
<bean id="..." >
    <security:intercept-methods>
        <security:protect method="com.apress.springrecipes.board.service.MessageBoardService.listMessages" access="ROLE_USER,ROLE_GUEST" />
    </security:intercept-methods>
</bean>

5.2.4 Method level security using @Secured or @RolesAllowed

Spring JSR-250

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

Example:

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
            <user name="bob" password="bobspassword" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

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

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

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

To say what roles are permitted access to a section of the JSP. Attribute access may have value or EL (but not both).

<security:authorize access="hasRole('supervisor')">do stuff</security:authorize>
<security:authorize ifAnyGranted="roles">do stuff</security:authorize>

Possible properties:

5.3 JMS

Basics JmsTemplate

5.3.1 Purpose of the JmsTemplate

5.3.2 How to declare a JMS Listener? Can a JMS Listener be a POJO?

Declaration of the JMS Listener JMS Listener as POJO

Yes - just register in XML inside a listener-container

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

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

Yes - with usage SimpleMessageListenerContainer (for basics) or DefaultMessageListenerContainer (for transactions).

5.4 JMX

Goals Overview

5.4.1 Role of the MBeanExporter

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

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

Yes - register as a bean and use MBeanExporter

<bean class="org.springframework.jmx.export.MBeanExporter">
    <property name="beans">
        <util:map>
            <entry key="bean:name=mine" value-ref="beanRef" />
        </util:map>
    </property>
</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 ends with MBean).

5.4.4 Purpose of the @ManagedResource, @ManagedAttribute and @ManagedOperation annotations

@ManagedResource(description = "some description")
public class MyJmxBean implements Foo {

	private int counter=0;

	@ManagedAttribute(description="Get counter value")
	public int getCounter() {
		return counter;
	}
	
	@ManagedOperation(description="Increase counter")
	public void increaseCounter() {
		this.counter++;
	
}

5.4.5 How to declare an MBeanServer

5.4.6 Accessing remote MBean (through a proxy)

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