Spring 3.1: a Walking Tour
-
Upload
josh-long -
Category
Technology
-
view
3.109 -
download
5
description
Transcript of Spring 3.1: a Walking Tour
© 2012 SpringSource, A division of VMware. All rights reserved
A Walking Tour of Spring 3.1
Josh Long, Spring Developer Advocate, SpringSource
Jürgen Höller, Principal Engineer, SpringSource
Mark Fisher, Senior Staff Engineer, SpringSource
Mark Pollack, Senior Staff Engineer, SpringSource
Dave Syer, Senior Staff Engineer, SpringSource
2NOT CONFIDENTIAL -- TELL EVERYONE
About Josh Long
Spring Developer Advocatetwitter: @[email protected]
33
Deployment Platforms: Becoming More Diverse
Tomcat
Application
Frameworks+ Libraries
Application
Frameworks+ Libraries
Application
Frameworks+ Libraries
Cloud PlatformWebSphere
44
Wide Variety of Data and Datastores
Not all data resides in relational databases cloud environments often suggest alternatives for scalability reasons HBase, Redis, Mongo, etc
Distributed caches add challenges as well not least of it all in terms of application-level access patterns GemFire, Coherence, etc
Hardly any standardization available JSR-107 – for caching – did not make progress for a long, long time finally getting picked up in Java EE 7, but again only for caching alternative datastore space is too diverse for standardization
55
Wide Variety of Web Clients
More and more client-side web technologies HTML 5 as a next-generation browser standard Adobe Flex as a rich client technology on the basis of Flash
Server-side state to be minimized or even removed completely in particular: no server-side user interface state strictly controlled user session state
JSF's state-centric approach not a great fit anymore except for special kinds of applications (which it remains very useful for) web application backends and web services based on JAX-RS / MVC style nevertheless: JSF keeps evolving – JSF 2.2 coming up in 2012
66
Key Elements of Spring: Ready for 2012 & Beyond
SimpleObject
SimpleObjects
Dep
ende
ncy
Inje
ctio
n
AOP
Portable Service Abstractions
More important than ever!
77
What's New?
Spring Framework 3.1
Spring Integration 2.1
Spring Data 1.0
Spring Security 3.1
88
Spring Framework 3.1: Selected Features
Environment abstraction and profiles Java-based application configuration Overhaul of the test context framework
Cache abstraction & declarative caching Servlet 3.0 based web applications @MVC processing & flash attributes
Refined JPA support
Hibernate 4.0 & Quartz 2.0
Support for Java SE 7
99
Environment Abstraction
Grouping bean definitions for activation in specific environments• e.g. development, testing, production
• possibly different deployment environments
Custom resolution of placeholders• dependent on the actual environment
• hierarchy of property sources
Injectable environment abstraction API
• org.springframework.core.env.Environment
Unified property resolution SPI
• org.springframework.core.env.PropertyResolver
1010
Bean Definition Profiles<beans profile="production">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClass" value="${database.driver}"/>
<property name="jdbcUrl" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
</beans>
<beans profile="embedded">
<jdbc:embedded-database id="dataSource" type="H2"><jdbc:script location="/WEB-INF/database/schema-member.sql"/><jdbc:script location="/WEB-INF/database/schema-activity.sql"/><jdbc:script location="/WEB-INF/database/schema-event.sql"/><jdbc:script location="/WEB-INF/database/data.sql"/>
</jdbc:embedded-database>
</beans>
1111
Environment Configuration
Associating specific bean definitions with specific environments• XML 'profile' attribute on <beans> element
•@Profile annotation on configuration classes
•@Profile annotation on individual component classes
Activating specific profiles by name• e.g. through a system property
• -Dspring.profiles.active=development
• or other means outside of the deployment unit• according to environment conventions
Ideally: no need to touch deployment unit across different stages/environments
1212
Java-Based Application Configuration
Application-specific container configuration• aligned with Spring 3.0's @Configuration style
• focus on customizing the annotation-based processing parts of Spring
Equivalent to XML namespace functionality• but not a one-to-one mapping
• 'natural' container configuration from an annotation-oriented perspective
Typical infrastructure setup• transactions
• scheduling
• MVC customization
1313
Application Configuration Example@Configuration
@EnableTransactionManagement(proxyTargetClass=true)
public class DataConfig {
@Bean
public PlatformTransactionManager txManager() {
return new HibernateTransactionManager(sessionFactory());
}
@Bean
public SessionFactory sessionFactory() throws Exception {
return new LocalSessionFactoryBuilder(dataSource())
.addAnnotatedClasses(Order.class, Account.class)
.buildSessionFactory();
}
@Bean
public DataSource dataSource() {
// ... configure and return JDBC DataSource ...
}
}
<tx:annotation-driven transaction-manager="txManager"proxy-target-class="true"/>
1414
Test Context Framework
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader=AnnotationConfigContextLoader.class,
classes={TransferServiceConfig.class, DataConfig.class})
@ActiveProfiles("dev")
public class TransferServiceTest {
@Autowired
private TransferService transferService;
@Test
public void testTransferService() {
...
}
}
1515
Interlude: "c:" Namespace
New XML namespace for use with bean configuration• shortcut for <constructor-arg>
• inline argument values
• analogous to existing "p:" namespace
• use of constructor argument names
• recommended for readability
• debug symbols have to be available in the application's class files
<bean class="…" c:age="10" c:name="myName"/>
<bean class="…" c:name-ref="nameBean"c:spouse-ref="spouseBean"/>
1616
Cache Abstraction
CacheManager and Cache abstraction• in org.springframework.cache
• which up until 3.0 just contained EhCache support
• particularly important with the rise of distributed caching• not least of it all: in cloud environments
Backend adapters for EhCache, GemFire, Coherence, etc• EhCache adapter shipping with Spring core
• JSR-107 a.k.a. JCache support coming in Spring 3.2
Specific cache setup per environment – through profiles?• potentially even adapting to a runtime-provided service
1717
Declarative Caching
@Cacheable
public Owner loadOwner(int id);
@Cacheable(condition="name.length < 10")
public Owner loadOwner(String name);
@CacheEvict
public void deleteOwner(int id);
1818
Servlet 3.0 Based Web Applications
Explicit support for Servlet 3.0 containers• such as Tomcat 7 and GlassFish 3
• while at the same time preserving compatibility with Servlet 2.4+
Support for XML-free web application setup (no web.xml)• Servlet 3.0's ServletContainerInitializer mechanism
• in combination with Spring 3.1's AnnotationConfigWebApplicationContext
• plus Spring 3.1's environment abstraction
Exposure of native Servlet 3.0 functionality in Spring MVC• standard Servlet 3.0 file upload behind Spring's MultipartResolver abstraction
• support for asynchronous request processing coming in Spring 3.2
1919
WebApplicationInitializer Example/**
* Automatically detected and invoked on startup by Spring's ServletContainerInitializer. May register listeners, filters, servlets etc against the given Servlet 3.0 ServletContext.
*/
public class MyWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.mycompany.myapp");
root.register(FurtherConfig.class);
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
...
}
}
2020
@MVC Processing & Flash Attributes
RequestMethodHandlerAdapter arbitrary mappings to handler methods across multiple controllers better customization of handler method arguments
HandlerMethodArgumentResolver HandlerMethodReturnValueHandler etc
FlashMap support and FlashMapManager abstraction with RedirectAttributes as a new @MVC handler method argument type
explicitly calling addFlashAttribute to add values to the output FlashMap an outgoing FlashMap will temporarily get added to the user's session an incoming FlashMap for a request will automatically get exposed to the
model
2121
Refined JPA Support
Package scanning without persistence.xml 'packagesToScan' feature on LocalContainerEntityManagerFactoryBean
building a persistence unit from @Entity classes within specific application packages
similar to AnnotationSessionFactoryBean for Hibernate 3 rolled into core LocalSessionFactoryBean for Hibernate 4
ideal for applications with a single default persistence unit
Consistent JPA setup by persistence unit name JPA specification quite strongly based on the notion of persistence unit
names @PersistenceContext / @PersistenceUnit referring to persistence unit names
now Spring's JpaTransactionManager and co support setup by unit name as well
as an alternative to referring to EntityManagerFactory beans directly
2222
Third-Party Support Updates
Hibernate 4.0 natively and through JPA native support in a dedicated org.springframework.orm.hibernate4
package dealing with package rearrangements in the Hibernate API
preserving compatibility with Hibernate 3.2+ in orm.hibernate3
Quartz 2.0 JobDetail and Trigger are now interfaces in the Quartz 2.0 API
whereas they traditionally were base classes in Quartz 1.x SchedulerFactoryBean now auto-adapts to Quartz 2.0 if present
JobDetail/CronTrigger/SimpleTriggerFactoryBean variants for Quartz 2.0 preserving compatibility with Quartz 1.5+ in the same support package
2323
Java SE 7
Spring 3.1 introduces Java SE 7 support making best use of JRE 7 at runtime support for JDBC 4.1 support for fork-join framework
Oracle's OpenJDK 7 released in summer 2011 IBM JDK 7 following not much later Java 7 could be the norm for new Java based projects soon
Spring Framework not being built against Java 7 yet build upgrade coming in Spring 3.2
2424
Summary
Spring serves as an enabler for modern Java architectures annotated components with dependency injection and declarative services flexible deployment options for any Java based target platform
Java SE 7 and Servlet 3.0 as common ground for years to come embedded application frameworks such as Spring are a perfect fit on top Spring as a programming and configuration model for cloud-based
deployments
Spring Framework 3.1 introduces several new key features environment abstraction and bean definition profiles cache abstraction and declarative caching web application deployment without web.xml compatibility with the latest platform standards and libraries
2525
Spring Integration 2.1
JSR-223 Scripting Support (Javascript, JRuby, Jython, Groovy)
AMQP/RabbitMQ
Spring Data: GemFire Redis MongoDB
Stored Procedures
Resource Inbound Channel Adapter
XPath Filter
Payload Enricher
FTP and SFTP Outbound Gateways
STS Templates
2626
Stored Procedures
inbound/outbound Channel Adapters
outbound Gateway
supports stored procs on: derby, db2, mysql, ms sql, oracle, postgres, sybase
supports sql functions on: mysql, ms sql, oracle, postgres
2727
Payload Enricher
Forward message to a nested flow and evaluate an expression against the result to enrich the payload
<int:enricher id="findUserByUsernameEnricher" input-channel="findUserByUsernameEnricherChannel" request-channel="findUserByUsernameServiceChannel" request-payload-expression="payload.username"> <int:property name="email" expression="payload.email"/> <int:property name="password" expression="payload.password"/></int:enricher>
2828
FTP and SFTP
Adding request/reply functionality in addition to the existing one-way Channel Adapters
<int-ftp:outbound-gateway id="gatewayGET" cache-sessions="false"local-directory="/tmp/gatewayGET"session-factory="ftpSessionFactory"request-channel="toGet"reply-channel="toRemoveChannel"command="get" command-options="-P"expression="payload.remoteDirectory + '/' + payload.filename"/>
Spring Data: Background and Motivation
Data access landscape has changed considerably RDBMS are still important and predominant• but no longer considered a “one size fits all” solution Spring has always provided excellent data access support Spring Data project goal is to “refresh” Spring’s data support for• Traditional: JDBC, JPA• New: Grid, NoSql, Hadoop Provide familiar and consistent Spring-based programming model• While retaining technology specific features and capabilities Remove boiler-plate code for writing a data access layer• Common interfaces that can be used across different technologies
Spring Data is an “umbrella project”
JPA - JDBC Extensions Hadoop – Big Data Storage and Analysis platform Gemfire – Distributed Data Grid Redis – Key Value Database MongoDB – Document Database Neo4j – Graph Database
Commons – shared abstractions• Repositories• Object Mapping QueryDSL – integration with type-safe query API
Spring Data Repositories
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
T save(T entity);
Iterable<T> save(Iterable<? extends T> entities);
T findOne(ID id);
boolean exists(ID id);
Iterable<T> findAll();
long count();
void delete(ID id);
void delete(T entity);
void delete(Iterable<? extends T> entities);
void deleteAll();}
public interface Repository<T, ID extends Serializable> {
}
3333
Spring Security 3.1
Multiple http elements
Stateless authentication
Improved Active Directory LDAP support
Crypto Module.
Disabling UI security (for testing purposes)
Erasing credentials after successful authentication
Clearing cookies on logout
Support arbitrary implementations of JAAS Configuration
34
CONFIDENTIALCONFIDENTIAL 34
Spring Security: Project Organization
Spring SecurityWeb
Core
LDAP OpenID ...
Spring Extensions: Security
SAML Kerberos
Spring Security OAuth
OAuth1a OAuth2
Oauth2 spec not yet final External lead 1.0.0.M6 release in pipeline
3.1.0 released Stable, mature
1.0.0 not yet released Partly external, low-activity
Luke Taylor (VMW), Rob Winch
Ryan Heaton,Dave Syer (VMW),
Vladimir Schaefer,Mike Wiesner (VMW)
Spring Social
Keith Donald, Craig Walls (VMW)
1.0.0 released Consumer for well-
known providers
NOT CONFIDENTIAL -- TELL EVERYONE
Questions?Questions?Say hi on Twitter: Say hi on Twitter:
@starbuxman @springsource@starbuxman @springsource
github.com/joshlong/a-walking-tour-of-spring-31/