Spring Core
Spring Professional Certification
Spring Professional Certification
-
- 1 / 227
-
Flashcards
XML Bean Definition Template
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframewok.org/schema/beans/spring-beans.3.0.xsd">
<!-- add bean definitions here -->
</beans>
2 forms of dependency injection
- constructor dependency injection
- setter dependency injection
constructor dependency injection
- enforce mandatory dependencies
- promote immutability
- concise for programmatic usage
<bean id="service" class="example.ServiceImpl">
<constructor-arg ref="repository"/>
</bean>
<bean id="repository" class="example.RepositoryImpl" />
NOTE: Ambiguity in args is NOT allowed!
<constructor-arg type="int">
<value>7</value>
</constructor-arg>
setter dependency injection
- allow optional dependencies and defaults
- have descriptive names
- inherited automatically
<bean id="service" class="example.ServiceImpl">
<property name="repository" ref="repository"/>
</bean>
<bean id="repository" class="example.RepositoryImpl" />
retrieving bean instance
(2 steps)
1. get application context
ApplicationContext context = new ClassPathXmlApplicationContext(...);
2. get bean from application context
OLD:
ClientService service = (ClientService) context.getBean("clientService");
NEW: since Spring 3.0
=> no more cast, type is a method param
ClientService service = context.getBean("clientService", ClientService.class);
=> no need for bean id if type is unique
ClientService service = context.getBean(ClientService.class);
Spring & Factory Beans
1) factory-method="getInstance"
useful for existing singeltons or factories
NOTE: getInstance() should always be static!
2) factory-bean="clientServiceFactory" factory-method="getNewInstance"
no need of class attribute
3) beans implementing FactoryBean interface are auto-detected
getObject() called by Spring automatically
NOTE: useful for generically build e.g. in-memory db at start time
loading application context
=> 3 examples for xml configuration
=> 1 example for java configuration
=> prefixes & wildcards
ApplicationContext ctx = new ClassPathXmlApplicationContext("com/example/appl-config.xml")
ApplicationContext ctx = new FileSystemXmlApplicationContext("C:\\etc\\appl-config.xml")
ApplicationContext ctx = new XmlWebApplicationContext(./config/appl-config.xml)
ApplicationContext ctx = new AnnotationConfigApllicationContext(Config.class)
Prefixes & wildcards:
classpath: = search in classpath but only first matching folder/jar is included
classpath*: = search in classpath and all sources (jar files & source folders) are included
file: = search in filesystem
http:
advantages of multiple config files
- application beans and infrastructure beans can be separated
- allows partitioning into logical groups (e.g. application modules)
- data source specific beans can be substituted easily (e.g. change of db)
- test and productive environment can be easily seperated
benefits of dependency injection
- bean is handed what it needs to work
- promotes programming to interfaces
- improves testability
- allows for centralized control over object lifecycle
namespaces: advanteges & characteristics
- simple and expressive configuration
- provide abstraction and semantic validation
- defined for categories of related framework functionality (aop, beans, context, jms, tx, ...)
- it's possible to write own namespace
JSR-250
common annotations
annotation for initialization phase
@PostConstruct / javax.annotation.PostConstruct
annotation for destruction phase
@PreDestroy / javax.annotation.PreDestroy
JSR-250 & Spring
Spring makes use of these annotations to trigger lifecycle events
@PostConstruct
@PreDestroy
NOTE: NOT @Autowired!
lifecycle phases of spring
- initialization phase
- use phase
- destruction phase
characteristics of initialization phase
application services
- are created
- are configured
- may allocate system resources
prepares for use / application is not usable until this phase is complete
characteristics of use phase
application services
- process client request
- carry out application behavior
99.99% of time is spent in this phase
characteristics of destruction phase
application services
- release any system resources
- are eligible for garbage collection
Shut Down
bean initialization steps
1. load bean definitions
- XML files are parsed
- bean definitions are loaded into context (each indexed under its id)
- BeanFactoryPostProcessor beans are invoked
2. initialize bean instances
- beans get instantiated
- setters called
- before init Bean Post Processors are called
- initializer called
- after init Bean Post Processors are called (proxies are created by Special BPP's)
3. bean ready for use
BeanFactoryPostProcessor:
- called when?
- common example
- 2 ways of declaration
1. only called once per xml before bean instantiation!
2. PropertyPlaceholderConfigurer
= substitutes ${variables} with values from
.properties files
NEW way with namespace:
<context:property-placeholder location="/WEB-INF/configuration.properties" />
OLD way:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/configuration.properties" />
</bean>
BeanPostProcessor:
- called when?
- common example
1. each processor is called once per bean before or
after bean is initialised
2. RequiredAnnotationBeanPostProcessor
= enforces that @Required properties are set
2 types of bean post processors
1. initializers
=> e.g. @PostConstruct = CommonAnnotationBeanPostProcessor
2. all the rest!
=> e.g. @Required = RequiredAnnotationBeanPostProcessor
ATTENTION: <context:annotation-config /> is needed!
Proxy Power
1) BeanPostProcessors may wrap beans in a dynamic proxy
2) Dynamic proxies add behaviors to beans (e.g. @Transactional)
bean destruction steps
1) bean instances are destroyed if instructed
@PreDestroy (e.g. useful for releasing resources and 'cleaning up'
2) destroy application context (context is NOT usable again)
bean scopes
- singleton (DEFAULT)
a single instance is used - prototype
new instance is created each time bean is referenced - session
new instance is created once per user session (web env.) - request
new instance is created once per request
(web env.) - custom
define own rules and new scope name (advanced)
define bean scope
<bean id="myBean" class="example.MyBean" scope="..." />
2 alternatives to @PostConstruct
1) declaring an init-method attribute in xml
<bean id="..." class="..." init-method="start" />
NOTE: method can have any visibility, but must have NO arguments! Useful for beans you do NOT control the implementation.
2) implementing InitializingBean interface
public void afterPropertiesSet() invoked automatically
NOTE: initialization technique used prior to Spring 2.5
NOTE: approaches can be mixed!
1. @PostConstruct
2. afterPropertiesSet() of InitializingBean
3. inti-method
2 alternatives to @PreDestroy
1) declaring a destroy-method attribute in xml
<bean id="..." class="..." destroy-method="close" />
NOTE: method can have any visibility, but must have NO arguments! Useful for beans you do NOT control the implementation.
2) implementing DisponibleBean interface
public void destroy() invoked automatically
bean definition inheritance
<bean id="abstractPool" class="..." abstract="true" />
NOTE: abstractPool will not be instantiated!
<bean id="poolA" parent="abstractPool" />
NOTE: bean definition without class or factory parameter is implicitly abstract!
overriding bean configuration
<bean id="defaultPool" class="...">
<property name="URL" value="aUrl" />
</bean>
<bean id="poolB" parent="defaultPool">
<property name="URL" value="bUrl" />
</bean>
NOTE: overrides URL property
<bean id="poolC" parent="defaultPool" class="example.PoolC">
<property name="URL" value="cUrl" />
</bean>
NOTE: overrides class type, not only property!
inner beans: advantages & characteristics
1) have no id (= anonymous bean)
=> cannot be referenced outside the bean scope
=> hides low-level beans
2) more manageable
3) avoid polluting the bean namespace
inner bean: property reference
WITHOUT inner bean:
<bean id="restaurantRepo" class="...">
<property name="policyFactory" ref="factory"/>
</bean>
<bean id="factory" class="example.PolicyFactory" />
WITH inner bean:
<bean id="restaurantRepo" class="...">
<property name="policyFactory">
<bean class="example.PolicyFactory"/>
</property>
</bean>
NOTE: => no id-attribute for inner bean!!!
inner bean: constructor reference
<bean id=outerBean" class="...">
<constructor-arg>
<bean class="innerBean" />
</constructor-arg>
</bean>
NOTE: inner bean as constructor-arg reference!
importing config files: example & default behavior
<beans>
<import resource="classpath:example/account-config.xml" />
...
</beans>
NOTE: relative path is default, good style however is to use full path!
bean naming convention
1) id can only hold a single value
=> use name attribute when multiple names are needed
2) some special characters are not allowed for id's (/:)
=>use name attribute when special characters are needed!
p Namespace: value example
OLD:
<bean id="..." class="...">
<property name="email" value="[email protected]"/>
</bean>
NEW:
<bean id="..." class="..." p:email="[email protected]"/>
p Namespace: reference example
OLD:
<bean id="..." class="...">
<property name="dataSource" ref="dataSource"/>
</bean>
NEW:
<bean id="..." class="..." p:dataSource-ref="dataSource"/>
p:<property-name>-ref=<reference>
p Namespace definition
Usage of p namespace requires definition!
xmlns:p="http://www.springframework.org/schema/p
NOTE: not specified in an XSD file -> no extra schemaLocation entry required!
util Namespace: characteristics
high-level configuration for common utility tasks
<property name="emailMappings">
<util:properties location="classpath:mail.properties" />
</property>
- defining collections <util:list />, <util:set />, <util:map />
- accessing constants (static fields) <util:constants />
- loading properties <util:properties />
util Namespace: collections
enhance default beans versions by allowing to:
- specify collection implementation type
- declare collection as a top-level bean
<util:set id="..." set-class="java.util.TreeSet" value-type="java.net.URI">
<value>http://server-a.example.com/</value>
<value>http://server-b.example.com/</value>
</util:set>