Spring AOP

Solves problem of cross cutting concerns, like:

  • logging & tracing
  • transaction management
  • security
  • caching
  • error handling
  • performance metrics instrumentation

Goals of Spring AOP:

  • avoid mixing of unrelated concerns in the same code (‘tangling‘ – e.g. business logic and security code)
  • avoid duplication of same/boilerplate code throughout many locations (‘scattering‘, e.g. transaction management)

Spring AOP only works with Spring Beans – cannot be used for Java Classes not managed by Spring (unlike AspectJ)

Pointcut expression matching syntax:

  • designator(return_type package.classname.methodname(params))

designator: e.g. execute – match when method called

return_type: *=wildcard, void, or specific type

package and classname can use * anywhere in the pattern as a wildcard:

  • package and classname are optional and can be omitted, eg perform(*) would match perform method on any class in any package
  • packageA.*.packageC : one wildcard package name between packageA and packageC
  • packageA..packageC: any number of packages
  • classname+ : + indicates any subclass of this class type, eg execution(* *..SomeRepository+.*(*)) – matches any implementation (+) of SomeRepository in any package (*..), and any method with any parameters

methodname can also use wildcard

params

  • ‘..’ indicates any parameters
  • methodname(int, ..) : indicates one int param followed by any other params

Using Annotations to declare an Aspect

@Aspect
public class LoggerAspect
{
    @Before(execution(* *ServiceImpl.*(*))
    public void logMethodCall()
    {
    ....
    }

}

– this pointcut declares an aspect for any method with any params on any class with name ending *ServiceImpl

Equivalent Bean configuration:

<context:component-scan base-package="example"/>
<aop:aspectj-autoproxy/>

<aop:config>
    <aop:aspect ref="loggerAspect">
        <aop:before pointcut="execution(* *ServiceImpl.*(*)" method="logMethodCall"/>
    </aop:aspect>
</aop:config>

<bean id="loggerAspect" class="example.LoggerAspect"/>

Getting Context on matching join points

  • Use JoinPoint as param on Advice impl method
  • Allows access to matching method signature (eg package, name, params)

Advice Types:

@Before

  • before call is made to matching method

@AfterReturning

  • on return from call to matching method

@AfterThrowing

  • matches if target throws an exception
  • Can rethrow as a new exception, but if you do, wrap the original exception so the original context from the exception is preserved

@Around

  • executes before and after method call
  • allows you to either continue with the about-to-be-called method or skip the call ( proceed() )

Methods that call other public methods that are ‘under advice’ in the same class do not get matched with the pointcut. For example, if Class A has methods a1() and a2(), and if the pointcut pattern matches both a1() and a2(), if a1() calls a2() internally, a1() will get the advice, but a2() will not. (KH TODO: would be a nice example to demonstrate this, and the following part too)

If two methods ‘under advice’ are in different classes, and one calls the other, then both methods will get the advice.

Core Spring Framework concepts

General:

  • bean creation and dependencies managed by Spring container
  • dependency configuration externalized to context config xml (or via annotations)
  • promotes ‘coding to interfaces’ – best practice to gain flexibility/maintainability
  • promotes loose coupling between classes
  • ability to change implementation classes via config, with no or little required code changes
  • Unit tests easily supported, since no Spring api dependencies in bean classes. DI can be used to inject mocks to support unit testing

The core features of Spring (the ‘Spring Triangle’): POJO/Simple objects are enhanced by the Spring framework by providing:

  • Dependency Injection (DI)
  • Aspect Oriented Programming (AOP)
  • Enterprise Service Abstractions

Bean defs

<bean id="..." class="..."/>
  • id is optional, but must be unique if used
  • name attribute can alternatively be used if you need to define multiple names (comma separated) for the same bean

Setter injection

<bean id="beanA" class="mypackage.ClassA"/>
<bean id="beanB" class="mypackage.ClassB">
    <property name="beanA" ref="beanA"/>
</bean>

Constructor injection

<bean id="beanA" class="mypackage.ClassA"/>
<bean id="beanB" class="mypackage.ClassB">
    <constructor-arg ref="beanA"/>
</bean>

Bean id is OPTIONAL (beans can be retrieved by type). Class is required.

<constructor-arg> can also pass literal values for constructor arguments, eg:

<constructor-arg value="abc"/>
<constructor-arg value="1"/>

Data type conversion on the arg values is implicit. Primitive types, Strings and Collections are supported. Can also support custom types by using a PropertyEditor.

Order of arg values in xml does NOT specify order of values to order of constructor args – Spring will attempt to match using a best guess based on types. e.g. if constructor has args (int, String) and you pass (String, int) as the constructor-args, it will be able to assign them correctly based on type. To remove ambiguity, specify an index to map to intended params:

    <constructor-arg value="1" index="0"/>
    <constructor-arg value="abc" index="1"/>

Can also specify by constructor arg name (in 3.1?) – name=”argument-name”

 

Constructor injection vs Setter injection

  • Using constructor injection enforces mandatory dependencies
  • Setter injection allow for optional dependencies and default values
  • follow standard Java design guidelines
  • if working with existing code, go with the approach that works
  • be consistent with your approach

Support for Collections

    • can inject collections, eg
<property name="names">
  <list>
    <ref bean="name1">
    <ref bean="name2">
    <ref bean="name3">
  </list>
</property>

List of values:

<property name="someListOfValues">
  <list>
    <value>example1</value>
    <value>example2</value>
  </list>
</property>

Factory Beans and Factory Methods

Using a factory bean to produce bean instances:

  • use factory-bean to define name of bean that produces bean instances, and factory-method to define what method to call to create instances
  • beans implementing FactoryBean interface are autodetected by Spring as being available to be used as factory beans
  • dependencies injected using a FactoryBean get their getObject() factory method called automatically… giving a simpler approach to implementing factories using a consistent api

<bean id=”example” class=”com.example.ExampleSingleton” factory-method=”getInstance”/>

– factory-method method must be static

Using a POJO as a FactoryBean:

public class ExampleFactory 
{ 
    public Example getInstance() { ... }
} 

<bean id="factory" class="example.FactoryBean"/> 
<bean id="example" factory-bean="factory" factory-method="getInstance"/>

Initializing app context for standalone app:

ApplicationContext context =
 new ClassPathXmlApplicationContext(new String[] {"application-context.xml"});

Initializing context from multiple config files:

ApplicationContext context =
 new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

Easy declarative transaction support – use of @Transactional

  • calling methods annotated with @Transaction are intercepted by Spring Framework – a transactional proxy is used to wrap your target class/method with transactional behavior

Bean Lifecycle

3 distinct phases:

  • Initialization: bean definitions are parsed, beans are instantiated and configured, DI performed, beans ready for use
  • Use: beans used by clients
  • Destruction: destruction callbacks invoked, beans destroyed, container shutdown

Initialization

  1. Bean config files loaded and parsed
  2. BeanFactoryPostProcessors executed
  3. For each bean:
    • Instantiate
    • Perform Dependency Injections
    • BeanPostProcessors executed
  4. Beans ready for use

 

During initialization there are two extension points for modifying beans:

  • BeanFactoryPostProcessors: all changes to the definitions of beans BEFORE they are created (example is the PropertyPlaceholderConfigurer which replaces ${} property placeholders in bean configs prior to beans being created). Occurs after bean files are parsed, but before beans are instantiated
  • BeanPostProcesors: perform changes to bean instances, for example to perform initialization logic. Occur AFTER instantiation and Dependency Injection. Usage: @PostContruct annotation, or init-method attribute in XML.

Bean Post Processors

Enabling @PostConstruct Annotations (and others)

<context:annotation-config/>
  • can be performed using JSR250 @PostConstruct annotation or init-method attribute on bean xml def
  • @PostConstruct and init-method are ONLY invoked after all DI has completed
  • @PostContruct is functionally equivalent to bean init-method attribute on bean def
  • this is the only point when beans know all DI has completed
  • if both defined, only init-method is executed since xml config always overrides annotations
  • Example BeanPostProcessors: @Required annotation (RequiredAnnotationBeanPostProcessor)

 

Destruction Phase

  • @PreDestroy annotation
  • destroy-method attribute in XML
  • implement DisposableBean interface (pre Spring 2.5)

Bean Inheritance

  • allows common bean config, eg properties, to be inherited
  • abstract=”true” : defines the base bean. Abstract/base beans are NOT instantiated
  • parent=”parent_bean_name” defines the parent that this bean inherits from
  • beans inheriting from a parent can change property values
  • any class not declared abstract=”true” can also be used as a parent
  • both parent and child classes are instantiated
  • child classes can override inherited properties and even the class

Importing Config Files

&ltimport resource="path/to/context.xml";/&gt;

Can use resource prefixes: classpath

Using the p namespace

Used as a shorthand or setting properties.

Add namespace definition:

xmlns:p="http://www.springframework.org/schema/p"

For this example:

<bean id="beanA" class="mypackage.ClassA"/>
<bean id="beanB" class="mypackage.ClassB">
    <property name="beanA" ref="beanA"/>
</bean>

You can now condense down to:

<bean id="beanA"/>
<bean id="beanB" p:beanA-ref="beanA"/>
</bean>

Property values: p:propertyname=”value”

Using the util namespace

Create a bean as a Set of Enum values from an Enum:

<util:set id=”fruit” value-type=”some.example.Fruit”>
<value>APPLE</value>
<value>PEAR</value>
</util:set>

XML configuration versus Annotations

  • XML always overrides Annotations

 

Bean Scopes

  • singleton – default scope – only single instance of bean created
  • prototype – creates new instance when bean requested
  • session – web specific – instance per user session
  • request – web specific – instance per user request
  • custom – user configurable

 

Spring Tool Suite (STS) / Eclipse bean support features

  • In project Properties, Spring / Beans Support – add list of app context files in use to enable autocomplete/validation features.
  • Group related app context files as ‘Config Sets’ to view consolidated view of bean configs and dependencies
  • From Spring Explorer view, right click Config Set and ‘Open Dependency Graph’ to see graphical view of all beans from all app context files in a Config Set

Rod Johnson joins Typesafe

Rod Johnson, founder of the Spring Framework and the SpringSource company, left Vmware/SpringSource a few weeks back and has resurfaced with Typesafe, founded by the developers of the Scala language.

It will be interesting to see in the coming months whether Johnson can add credibility to Scala to help enterprise adoption of the language.

Rod Johnson, founder of the Spring Framework, leaves VMWare/SpringSource

When Rod Johnson started the Spring Framework back in the early 2000s, he showed J2EE developers that there are better ways to build enterprise Java apps, and he provided the framework to help you do it. Anyone having experienced the pain of developing EJB 2.x beans during this time with it’s clunky api and verbose deployment descriptors and then since worked with the Spring Framework can attest to the huge benefits of developing apps using Spring’s much simpler, lightweight approach. Spring’s success has arguably been a significant influence on the ‘ease of use’ focus for the simplifications and improvements made in EE5 and EE6 in recent years.

Rod recently announced that he’s leaving VMWare to pursue other interests – I wish him success in his future endeavors and thanks for the impact you’ve made to enterprise Java development in the past 10+ years.