<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>
1.2.2 How to declare a destroy method in a Spring bean?
JSR-250: annotation @PreDestroy on method
Implement DisposableBean#destroy
XML: <bean ... destroy-method="finish">
1.2.3 Default bean instantiation policy: when are beans instantiated?
For Singleton - when app context is created / parsed
For Prototype - anytime the bean is required
Lazy loading instantiation policy (when first referenced) - attributes "lazy-init" on the <bean/> element or "default-lazy-init" on the <beans/> element
Mem:
Order (by component): XML context, BFPP, new, set, BPP#before, init[@PostConstruct, Init#afterPropertiesSet, init-method], BPP#after, dispose[@PreDestroy, Disp#destroy, destroy-method]
Sequence (by type): init / destroy order is: (@) annotation, (#) interface method, (-) xml attribute
1.2.x What is a FactoryBean?
Spring interface with methods getObject90, getObjectType and isSingleton
Beans implementating of such interface are autodetected
Used to JNDI lookup, creating proxies, etc.
Underlying basis for Spring's IoC functionality
1.3 Annotations
1.3.1 Enabling component-scanning
Use <context:component-scan /> for @Component (general), @Controller (web), @Repository (dao) and @Service (service)
Options:include-filter and context:exclude-filter elements
Components (including JAR dependencies) are scanned at startup
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.
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) - to define specific bean name if desired or needed (e.g. to choose one of many beans of same type)
the bean name is:
considered as a default qualifier value (when no qualifier is defined)
auto-generated when not specified (but not accessible)
avoid using name when possible
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.
<context:component-scan /> can also do what <context:annotation-config /> does but <context:component-scan /> also scans packages to find and register beans within the application context.
@Required goes on setters, not fields
@PostConstruct, @PreDestroy goes on methods
1.3.6 Other
Other annotations
@Scheduled(fixedDelay=5000)
@Async
SpEL
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?
The value of a map key or value, or a set value, can also again be any of the following elements: bean | ref | idref | list | set | map | props | value | null
If you need to refer to this outside a <bean /> or need to specify list/set/map type, use util namespace (i.e. util:list)
Use the "parent" attribute to inherit (and merge entries) from a parent collection.
Strongly typed collections - Entries will be converted to the appropriate type prior to being added to the Collection
1.4.3 How to create an ApplicationContext? 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
classpath:
file:
http:
Reference to configuration file
new ClasspathXmlApplicationContext("/com/mine/app-config.xml");
Implementations of ApplicationContext
ClasspathXmlApplicationContext
Default prefix is classpath
Starts looking from root of classpath regardless of whether specify "/"
FileSystemXmlApplicationContext
Default prefix is file
Uses relative path even if specify "/", but "file:/mine" forces an absolute path
XmlWebApplicationContext
Default web app (file) is /WEB-INF/applicationContext.xml
Uses path relative to web application
1.4.4 How to externalize constants from a Spring XML configuration file into a .properties file?
@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
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.
Id - must be unique (legal characters are limited)
Name - can specify multiple names separated by comma, semicolon or space (allows more characters in name such as slashes)
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.
1.4.9 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
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?
Instance (non-static) factory method: specify "factory-bean" and "factory-method" attributes
Static factory method: specify "class" and "factory-method" attributes
<!-- 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
<import resource="local path" />, path is relative to the definition file
Prefer "multiple resource locations" as configs are unaware of each other
Use classpath:/.. or file:.. if need an absolute path
public class Foo {
@Value("T(java.lang.Integer).MAX_VALUE")
private Integer myValue;
}
1.4.13 Other annotations
@Scope("prototype") - to change default (singleton) scope
@DependsOn - beans on which the current bean depends
1.5 JavaConfig
1.5.1 Usage of the @Bean and @Configuration annotations
@Configuration
Declares a class to be a Spring's Java based configuration
Must have default constructor or none
@Bean - declares a method as spring bean (in a Java based configuration). Properties are:
initMethod (redundant because can call method)
destroyMethod
name (aliases)
autowire (defaults to no)
Other usefull annotations:
@Primary - indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency
@Import - to reference another @Configuration (you can't just call it directly as calls must be in the correct order in dependency graph)
@ComponentScan("com.acme.app.services") - same as <context:component-scan/> in XML configuration
@PropertySource("classpath:/com/acme/app.properties") - see example:
@Configuration
@PropertySource("classpath:/com/acme/app.properties")
public class AppConfig {
@Inject Environment env;
@Bean
public MyBean myBean() {
return new MyBean(env.getProperty("bean.name"));
}
}
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
Mock Objects (JNDI, Servlet API, etc.)
Unit Testing support Classes (ReflectionTestUtils, ModelAndViewAssert, etc.)
Isolation environment & spring configuration
Integration testing
To manage Spring IoC container caching (by fixture) between test execution.
To provide Dependency Injection of test fixture instances.
To provide transaction management appropriate to integration testing.
To supply Spring-specific support classes that are useful in writing integration tests.
Support for JDBC, annotations, Spring MVC, etc.
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:
Annotation @ContextConfiguration uses sufix ${test class}-context.xml to define default XML configuration (e.g. FooTest-context.xml for test FooTest.java) and attribute locations (e.g. locations={"config.xml"}) to to define more XML configurations
@Autowire does not work on constructors
The context is cached across test fixtures unless you use @DirtiesContext (to force spring application context recreation).
The "inheritLocations" attribute of the annotation (default to true) inherits (appended to current list) the super-classes locations
@WebAppConfiguration - to ensure that a WebApplicationContext is loaded for your test
@ContextHierarchy - to define a hierarchy of ApplicationContexts for integration tests
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(classes = AppConfig.class),
@ContextConfiguration(classes = WebConfig.class)
})
public class WebIntegrationTests {
// class body...
}
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 - to override default rollback policy
@Transactional - on class or method, can set propagation/isolation/etc
@Rollback - on class or method
@BeforeTransaction (@Before is inside txn)
@AfterTransaction (@After is inside 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
AOP is technology to solve cross-cutting concerns (authentication, logging, transacations, etc.)
Spring uses AOP proxy: object created by AOP to implement the aspect contracts.
The goal is to eliminate:
Tangling - mixing of concerns
Scattering - code duplication
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.
Targeted object: object being advised
Aspect: a modularization of a concern that cuts across multiple classes (packaged advice and pointcut).
Joinpoint: a point during the execution of a program (when advice is mapped to be executed), 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: the place in code where code can be injected (expression to identify join point). 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.
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:
Definition: execution([modifiers or annotations] ReturnType [FullyQualifiedClassName.] MethodName ([Arguments]) [throws ExceptionType])
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
Can only be used for methods
Limited pointcut syntax
Doesn't get called if caller makes direct calls (due to proxy)
Final classes cannot have aspects applied (proxy does not work)
3. Data Access and transactions
3.1 General
3.1.1 The rationale for having the DataAccessException hierarchy.
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
3.1.2 Definition of a DataSource in the Spring configuration
applicable on public methods or class (not applicable on non-public methods - there will be no error, but no transaction will be applied)
not recommend on interfaces b/c not all proxies will take them
requires JDK 5
3.4.4 Usage of TransactionTemplate for programmatic transaction management (you simply need to understand a basic example based on the TransactionTemplate).
Takes transaction manager in constructor
Passes TransactionStatus to TransactionCallback which lets you call status.setRollbackOnly()
3.4.5 Transactions and exception management: what is the default rollback policy? Can it be overridden?
Default policy is rollback for a RuntimeException.
Default policy can be overriden - for the @Transactional annotation, specify rollbackFor or noRollbackFor when passing Class or rollbackForClassname/noRollbackForClassname when passing Strings.
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:
timeout - specified in seconds
readOnly - true or false
isolation - Isolation.READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ or SERIALIZABLE
propagation - Propagation.REQUIRES_NEW, REQUIRED, etc. (see chapter 3.4.7)
rollbackFor or rollbackForClassname - list of exceptions
noRollbackFor or noRollbackForClassname - list of exceptions
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:
REQUIRED (default) - If there’s an existing transaction in progress, the current method should run within this transaction. Otherwise, it should start a new transaction and run within its own transaction.
REQUIRES_NEW - The current method must start a new transaction and run within its own transaction. If there’s an existing transaction in progress, it should be suspended.
SUPPORTS - If there’s an existing transaction in progress, the current method can run within this transaction. Otherwise, it is not necessary to run within a transaction.
NOT_SUPPORTED - The current method should not run within a transaction. If there’s an existing transaction in progress, it should be suspended.
MANDATORY - The current method must run within a transaction. If there’s no existing transaction in progress, an exception will be thrown.
NEVER - The current method should not run within a transaction. If there’s an existing transaction in progress, an exception will be thrown.
NESTED (unique Spring feature) - If there’s an existing transaction in progress, the current method should run within the nested transaction (supported by the JDBC 3.0 save point feature) of this transaction. Otherwise, it should start a new transaction and run within its own transaction.
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:
Dirty reads (Uncommitted Dependency) - A dirty read occurs when a transaction is allowed to read data from a row that has been modified by another running transaction and not yet committed.
T1 Read
T2 Update
T1 Read will be temporary and invalid.
T2 Rollback
Nonrepeatable read - A non-repeatable read occurs, when during the course of a transaction, a row is retrieved twice and the values within the row differ between reads.
T1 Read
T2 Update
T1 Read value will be different
Phantom read - A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.
T1 Read
T2 Insert
T1 Read will contain additional rows.
The options to solve the read phenomena are:
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
4.1 General configuration
<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.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
Identifies correct view to call (to resolve the view implementation based on a given logical name). All handler methods in the Spring Web MVC controllers must resolve to a logical view name. View resolver can not handle absolute path (to the view).
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)
Can be chained (using the "order" attribute). InternalResourceViewResolver must be last.
RedirectView or "redirect:"
Some of implementations:
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
ContentNegotiatingViewResolver - maps based on request file name or Accept header
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
Dispatch Servlet
Front controller delegating to web infrastructure beans (handler mappings, view resolvers, type converters) and calling controllers/views
Scenario of handling 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.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:
Define listener so it loads the root ApplicationContext before initializing the servlet as:
4.2.2 General usage of the @Controller and @RequestMapping annotations
@Controller - annotates a class containing @RequestMapping on methods returning ModelAndView, String, void, etc.
@RequestMapping:
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 restrict by type or filter by params/headers (e.g. method=RequestMethod.GET)
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.
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
Ant style globs: @RequestMapping("/myPath/*/pets/{petId}")
@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)
A method annotated with @RequestMapping returns the view name - i.e. logical name of the view (to be determined by view resolver). For example, one can add a prefix/suffix to all strings returned, void (if the method handles the response directly), etc.
Main parameter types of @RequestMapping method:
Servlet API - HttpSession, HttpServletRequest, HttpServletResponse
Other - Command or Form objects, Errors, SessionStatus
MEM: Method can not return absolute path to view.
4.2.4 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.
@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
If you specify a multipart file resolver, the request is inspected for multiparts.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
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
@RequestMapping defines URI to resource, action (what to do with the resource) is defined by HTTP method:
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 (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
Send an HTTP response code with the response. For example, @ResponseStatus(HttpStatus.CREATED).
If defined on the method, sends that header.
If defined on an exception, only sends if that error occurs.
An empty body can be used for REST so no view is used.
@ResponseStatus annotation can go on @RequestMapping method or an exception class.
4.3.5 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:
@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?
HttpMessageConverter to convert to / from HTTP
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 params, 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 and general configuration of the RMI Service Exporter
Goals:
Handle server side of RMI interaction
Bind to registry
Expose endpoint (used for everything except EJB; EJB already has mechanism to export remote)
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
5.1.4 Difference between the RMI Service Exporter and the HttpInvoker
HttpInvoker uses HTTP POST while RMI one uses RMI.
Bean classes to expose bean are HttpInvokerServiceExporter or RmiServiceExporter with the definition of service (reference to POJO implementing serviceInterface) and service interface (interface classname).
Bean classes to connect bean are HttpInvokerProxyFactoryBean or RmiProxyFactoryBean with the definition of service URL (endpoint to the bean) and service interface (interface classname).
The serviceName is specified as the name of the bean because default is to use BeanNameUrlHandlerMapping.
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:
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.
<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:
FilterSecurityInterceptor - checking role (authorization)
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)
Components: message, destination, connection, session, message producer and consumer
JMS message types: TextMessage, ObjectMessage, MapMessage, etc.
Destination is where we listen for a message
Response-destination is needed if the method doesn't return void
Configuration:
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
JmsTemplate
Reasons to use: see chapter 5.3.1
Instances of the JmsTemplate class are thread-safe once configured.
All send methods put message on queue and resume.
All receive methods are blocking / synchronous.
MessagePostProcessor interface gives you access to the message after it has been converted.
Properties:
Connection Factory (e.g. SingleConnectionFactory or CachingConnectionFactory - required
Use "defaultDestination" (destination does not need to be specified for each send / receive call) - Spring bean (reference name) or DestinationResolver.
Methods (use MessageCreator - if need to map object to/from Message for nonstandard type):
convertAndSend() - delegates conversion to the MessageConverter bean (set on the JmsTemplate) and then sends message
receiveAndConvert() - waits to receive message and then delegates to the MessageConverter bean (set on the JmsTemplate).
execute() - use for SessionCallback and ProducerCallback
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
Use org.springframework.jmx.export.annotation.AnnotationMBeanExporter to detect @ManagedResource annotations
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 ends with MBean).
5.4.4 Purpose of the @ManagedResource, @ManagedAttribute and @ManagedOperation annotations
@ManagedResource(objectName="mine") - identifies class as MBean
@ManagedAttribute – expose field to JMX – place on getter and setter
@ManagedOperation – expose method to JMX
@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
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.