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

(Page views: 263)

Leave a Reply