Upload
josh-long
View
849
Download
0
Embed Size (px)
DESCRIPTION
In this talk, originally presented at JavaZone, in Oslo, Norway, I introduce the broad swath of supported inversion-of-control options in Spring's component model, and then introduce some more advanced features of the component model.
Citation preview
© 2009 VMware Inc. All rights reserved
IOC Options in Spring
Josh Long @starbuxmanSpring Developer AdvocateSpringSource, a division of VMware
2
About Josh Long
engineer, advocate for SpringSource
blog.springsource.org
@starbuxman
3
About Josh Long (cont’d)
Wrote “Getting Started with Spring Roo”
• free book download: http://bit.ly/ppv1Lx
• SpringSource.org/roo for information
4
About SpringSource
SpringSource is the organization that develops the Spring framework, the leading enterprise Java framework
SpringSource was acquired by VMware in 2009
VMware and SpringSource bring you to the cloud and deliver on the mission of “build, run, manage”
• established partnerships with the major players in the business, including Adobe, SalesForce, and Google to help deliver the best experience for Spring users across multiple platforms
Leading contributor to projects like Apache HTTPD and Apache Tomcat
5
At its core, the Spring Framework...
Provide comprehensive infrastructural support for developing enterprise Java™ applications
• Spring deals with the plumbing
• So you can focus on solving the domain problem
6
Spring’s aim:
bring simplicity to java development
6
web tier web tier & &
RIARIA
web tier web tier & &
RIARIA
service tierservice tierservice tierservice tier batch batch processingprocessing
batch batch processingprocessing
integration integration & &
messagingmessaging
integration integration & &
messagingmessaging
data data accessaccess
/ NoSQL / / NoSQL / Big DataBig Data
data data accessaccess
/ NoSQL / / NoSQL / Big DataBig Data
mobilemobilemobilemobile
tc Servertc ServerTomcatTomcat
JettyJetty
lightweightlightweight
CloudFoundryCloudFoundryVMForce VMForce
Google App EngineGoogle App EngineAmazon Web ServicesAmazon Web Services
the cloud: the cloud:
WebSphereWebSphereJBoss ASJBoss ASWebLogicWebLogic
(on legacy versions, too!) (on legacy versions, too!)
traditionaltraditional
The Spring frameworkThe Spring framework
7
Application Configuration
A typical application system consists of several parts working together to carry out a use case
• lots of collaborating objects
component Bcomponent Bcomponent Bcomponent B
component Ccomponent Ccomponent Ccomponent C
component Acomponent Acomponent Acomponent A
8
Application Configuration
A typical application system consists of several parts working together to carry out a use case
• lots of collaborating objects
MyServiceMyServiceMyServiceMyService
DB Driver DB Driver configurationconfiguration
DB Driver DB Driver configurationconfiguration
DataSourceDataSourceDataSourceDataSource
9
Spring Has Only One Type of Component: a POJO
POJO: Plain ‘Ol Java Object
• standard objects
• objects have dependencies
public class CustomerRepository {
// ‘depends’ on a database connection private javax.sql.DataSource dataSource; }
• objects have lifecycles:
Connection conn = ... ; conn.open() ;...conn.close();
beginning andend of the lifecycle
10
The Spring ApplicationContext
Spring Beans are Managed by An ApplicationContext
• whether you’re in an application server, a web server, in regular Java SE application, in the cloud, Spring is initialized through an ApplicationContext
• In a Java SE application:
• In a web application, you will configure an application context in your web.xml
<servlet> <servlet-name>Spring Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/myAppContext*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
ApplicationContext ctx = new AnnotationConfigApplicationContext( “com.foo.bar.my.package”); or ApplicationContext ctx = new ClassPathXmlApplicationContext( “my-context.xml”);
11
The Spring ApplicationContext
Spring Manages the beans you tell it to manage
• use annotations (JSR 250, JSR 330, native)
• XML
• Java configuration
• component scanning
You can of course use all of them! Mix ‘n match
All configuration styles tell the ApplicationContext how to manage your beans
12
Spring, a walking tour
Demos:
• introduce the tool chain
• how to “setup” Spring
• basic dependency injection
• annotations (JSR 250, JSR 330, native)
• xml
• java configuration
13
@Qualifiers
Provide a way to discriminate for @Autowired / @Inject for ambiguous types
• by bean name (meh)
• by presence of annotation (yay!)
14
Spring, a walking tour
Demos:
• Qualifiers
15
Working with Lots of Beans
To Modify or Transform Beans in the Context...
• You need to “select” the beans you want to modify
• You need to provide the code that represents the modification or augmentation
16
Working with Lots of Beans
One way to selectively augment beans at the lower level:
• BeanPostProcessor
• are regular beans and are run after the configured beans have been created, but before the context is finished setting up
• BeanFactoryPostProcessor
• is run before any of the beans definitions are realized
• comes before BPP
A more natural alternative is Spring’s AOP support
• built on top of AspectJ
• provides a very convenient, powerful way to solve cross cutting problems
17
Spring, a walking tour
Demos:
• Bean*PostProcessor
• AspectJ
18
Life Cycles
Life Cycles for different folks
• “safe and consistent” - use the interfaces
• InitializingBean, DisposableBean
• correspond to init-method and destroy-method attributes
• Simple and component-centric : use the annotations
• @PostConstruct, @PreDestroy
• correspond to init-method and destroy-method attributes
• More power: SmartLifecycle
• gives you the ability to dynamically start and stop beans in a certain order as well as to query whether the bean’s been started or not.
19
Life Cycles
Spring beans have scopes
• default: singleton
• can be:
• prototype
• HTTP session
• HTTP request
• HTTP application (servlet, basically)
• “step” in Spring batch
• thread-local
• Spring Web Flow “flow” scoped
• Spring Web Flow “conversation scoped”
• Spring Web Flow “view” scoped (in JSF)
• Activiti BPMN2 process-scoped
• any scope you want. It’s simple to add your own!
20
Spring, a walking tour
Demos:
• life cycle callbacks
• scopes
21
Getting Beans from Strange Places
FactoryBeans
Spring Expression Language
• convenient way to get at values and inject them
Spring environment specific beans (profiles)
• introduced in Spring 3.1
• make it easy to conditionally define an object based on some sort of runtime condition
22
Getting Beans from Strange Places
FactoryBeans
• interface that’s used to provide a reusable definition of how to create a complicated object with many dependencies
• Related: Java configuration, and builders
• prefer both over FactoryBeans where possible
23
Getting Beans from Strange Places
Spring Expression Language
• convenient way to get at values and inject them
• Andy Clement’s a genius
• like the Unified JSF EL, on steroids
• Can be used in Java, XML
• @Value(“#{ ... }”) or value = “#{ .. }”
24
Getting Beans from Strange Places
Spring profiles
• @Profile(“production”) @Configuration ...
• <beans profile = ‘production’> ... </beans>
• Use System properties or simply specify the active profile on the environment
• Use ApplicationContextInitializer in web applications
25
Spring, a walking tour
Demos:
• FactoryBeans
• SpEL
• Profiles
26
Summary / Questions
code: git.springsource.org:spring-samples/spring-samples.git
blog.springsource.org
springsource.com/developer/sts