Spring


AnnotationConfigApplicationContext | BeanFactory | 

Container


Setter Injection can expose an Object in an inconsistent state. Good if dependencies are not known in advance and only available at runtime.

Constructor-injection enforces the order of initialization and prevents circular dependencies

BeanFactory -> PropertyPlaceholderConfigurer -> BeanFactoryPostProcessor -> ApplicationContextAware -> BeanFactoryAware ->


Control Lifecycle of Spring Bean


  1. InitializingBean and DisposableBean callback interfaces
  2. Other Aware interfaces for specific behavior
  3. custom init() and destroy() methods in bean configuration file
  4. @PostConstruct and @PreDestroy annotations

Spring Bean Scopes

  • Singleton - Default
  • Prototype - Instance per Request
  • Request - Instance per http request
  • Session - Instance per http session
  • Global-Session - Instance per global http Session. global-session is something which is connected to Portlet applications. Multiple Portlets Share 1 Global Session.


Injecting beans created outside the container

The @Configurable annotation marks a class as eligible for Spring-driven configuration
The default name for a bean is the fully-qualified name of its type
Spring will configure new instances of the annotated type using a bean definition (typically prototype-scoped) with the same name as the fully-qualified type name . So omit the id from Bean definition.
@Configurable(autowire=Autowire.BY_TYPE / Autowire.BY_NAME )

AOP

  • Done using proxies
  • CGLIB - When the Beans don't implement Interfaces.
  • JVM Proxy - All Beans must implement an Interface.
  • Spring uses the AspectJ pointcut expression language by default
  • Spring supports Aspects on methods only
  • Spring performs weaving at runtime
  • It is not possible to have aspects themselves be the target of advice from other aspects
  • protected methods are by definition not intercepted. Only public methods.
  • final methods can't be advised.
  • CGLIB included in spring-core since 3.2 - to force use of CGLIB - proxy-target-class="true" on AopConfig.


Spring AOP vs AspectJ
Spring can advice only Spring managed beans. AspectJ can manage beans outside the container.
Spring can only advice methods(). AspectJ is much more powerful.


Aspect : Is the Concept / Feature that is to be applied
Join Point : The join point is a point of execution in the base code 
Pointcut : A predicate that matches join points. (is an expression)
AdviceAction taken by an aspect at a particular join point. (“around,” “before” and “after” advice)
ProceedingJoinPoint : Handle to the Join Point

Advice is associated with a Pointcut Expression and runs at any Join Point matched by the Pointcut



  1. Create the Aspect class - Using @Aspect
  2. Define the Advice - What needs to be done ex - Log 
  3. Define the Pointcut Expression - What all methods will the Advice apply to - void pointcutFunction() 
  4. Link Pointcut with Advice using Type ( Around / Before / After ) @Around( value=pointcutFunction( args ) )
  5. Spring config <aop:aspectj-autoproxy/> / @EnableAspectAutoProxy
  6. @Component - for component scanning. 

Advice Types

@Before - Runs before the Join Point
@AfterReturning - Runs when method returns normally
@AfterThrowing - When the matched method throws exception. Can be 
restricted to a particular type of Exception.
@After - When method execution exits. Normally or otherwise.
@Around - Has to call PJP.proceed()


ProceedingJoinPoint pjp;
pjp.getTarget().getClass(), pjp.proceed(),

Only works with Spring managed beans - http://forum.spring.io/forum/spring-projects/aop/100627-pointcut-on-spring-jdbc-classes-not-working

1. Define Pointcut where the Advice will be applied.
2.

http://eggsylife.co.uk/2010/02/03/spring-annotation-based-aop-and-intercepting-the-ball/

JDBC & Transaction

RowMapper
ResultSetMapper
RowCallbackHandler

PlatformTransactionManager : 


Global Transaction



  • Manages Multiple Transactional resources (DB & Message Queues).
  • Application Server is required which uses JTA (which in turn requires JNDI).
    • other options - JOTM, Atomikos
  • EJB CMT can be used to perform Global Transactions (declarative).



Local Transaction


  • Resource Specific - JDBC
  • Can't handle Multiple Transactional Resources
  • Invasive to programming model
Spring provides Consistent programming model so that once code is written it can be used across different transaction management strategies in different environments.

PlatformTransactionManager interface
TransactionDefinition interface specifies

  • Isolation - Can the Transaction see un-commited writes.
    • DEFAULT - Isolation level of Underlying Datastore. 
    • READ_COMMITED - Dirty Reads - No, Non-Repeatable read - Yes, Phantom Read - Yes.
    • READ_UNCOMMITED - Dirty Reads - Yes, Non-Repeatable read - Yes, Phantom Read - Yes.
    • REPEATABLE_READ - Dirty Reads - No, Non-Repeatable read - No, Phantom Read - Yes.
    • SERIALIZABLE - Dirty Reads - No, Non-Repeatable read - No, Phantom Read - No.
  • Propagation - Defines how a transactional method behaves when it is executed within an existing transaction context.

  • MANDATORY
    Support a current transaction, throw an exception if none exists.

    NESTED
    Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.

    NEVER
    Execute non-transactionally, throw an exception if a transaction exists.

    NOT_SUPPORTED
    Execute non-transactionally, suspend the current transaction if one exists.

    REQUIRED ( Default )
    Support a current transaction, create a new one if none exists.

    REQUIRES_NEW
    Create a new transaction, and suspend the current transaction if one exists.

    SUPPORTS
    Support a current transaction, execute non-transactionally if none exists.
    no txn > NEVER > NON_SUPPORTED > SUPPORTS > NESTED > REQUIRED > REQUIRES_NEW > MANDATORY > txn only  

The NESTED behavior makes nested Spring transactions to use the same physical transaction but sets savepoints between nested invocations so inner transactions may also rollback independently of outer transactions. This may be familiar to JDBC aware developers as the savepoints are achieved with JDBC savepoints, so this behavior should only be used with Spring JDBC managed transactions

More details on the scopes at the link below.

http://stackoverflow.com/questions/2007097/unexpectedrollbackexception-a-full-scenario-analysis


  • Timeout - Transaction gets rolled back after the Timeout.
    • Default is -1.Never time out.
  • Read-only Status - Defines a method to be Read-Only.
    • Default is FALSE.

Instances of PlatformTransactionManager


  • DatasourceTransactionManager
  • JtaTransactionManager
  • HibernateTransactionManager

Declarative Transaction Management

  • Uses Spring AOP
  • Lowest Granularity is Method Level
  • Declarative Rollback Rules
  • Transaction behaviour can be customised using AOP in case of Rollback.

Implementing Transaction Management

  • @EnableTransactionManagement - to enable TM within the container.  Add to any @Configuration class in the beans definitions.
  • @Transactional - Only to public methods. Is a marker for the method that informs runtime that the method is accepting the Transaction behaviour.
  • TransactionInterceptor 
  • PlatformTransactionManager

Rolling Back a Declarative Transaction


<tx:method name="get*" read-only="true" rollback-for="NoProductInStockException"/>
<tx:method name="updateStock" no-rollback-for="InstrumentNotFoundException"/>
  • Default Configuration - Rollback in the case of runtime, unchecked exceptions (subclass of RuntimeException). Errors will also result in a rollback. 
  • As soon as the Exception is thrown the surrounding transaction is marked as rollback-only.
  • Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration



Batch



Spring RESTful Services


@Controller - Servlet Controllers
@RestController - For REST services 
@ RequestMapping - @RequestMapping(value="/dictionary", method=RequestMethod.GET) - Request resolution. At class level & method level. 
@RequestBody - void method( @PathVariable("word") String id, @RequestBody Word word  )
@ResponseBody  - 
@ResponseStatus  - @ResponseStatus(HttpStatus.MOVED_PERMANENTLY)
@Exceptionhandler - @Exceptionhandler(NotFoundException.class)

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}
@RequestMapping maps all HTTP operations by default. Use@RequestMapping(method=GET) to narrow this mapping.
@RequestParam binds the value of the query string parameter name into the nameparameter of the greeting() method

No comments:

Post a Comment