SlideShare a Scribd company logo
1 of 53
Download to read offline
Tailoring Spring for Custom Usage

   • Josh Long, SpringSource, a division of VMware




   1

Sunday, February 19, 12
About Josh Long (Spring Developer Advocate)


                          @starbuxman
                          josh.long@springsource.com




                                                  th
                                                   s i
                                                     is
                                                         im
                                                          po
                                                              rta
                                                               nt
                                                                 !
   2

Sunday, February 19, 12
Agenda

   Explore the value of a framework
   Exploit some of the lesser known, but powerful, extension
     hooks in the core Spring framework
   QA




   3

Sunday, February 19, 12
Spring’s aim:
   bring simplicity to java development
                                                                      data
    web tier                                         integration
                                         batch                       access
      &               service tier                        &                           mobile
                                      processing                   / NoSQL /
     RIA                                             messaging
                                                                   Big Data


                                     The Spring framework
 the cloud:                            lightweight                    traditional
        CloudFoundry                                                        WebSphere
                                                   tc Server
          VMForce                                                            JBoss AS
                                                    Tomcat
      Google App Engine                                                     WebLogic
                                                      Jetty
     Amazon Web Services                                                (on legacy versions, too!)




                                                                                                     4

Sunday, February 19, 12
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



   5

Sunday, February 19, 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




   6

Sunday, February 19, 12
Spring Integration rules!!




                          Not confidential. Tell everyone.   7


Sunday, February 19, 12
...but??!?
                          ...what if it doesn’t do what I want?




   8

Sunday, February 19, 12
What is Spring Integration?
FLEXIBLE




                                         v




                          Not confidential. Tell everyone.   9


Sunday, February 19, 12
10

Sunday, February 19, 12
do NOT reinvent
                          the Wheel!




   11

Sunday, February 19, 12
The Open/Closed Principle

   "software entities (classes, modules, functions, etc.) should
     be open for extension, but closed for modification”
          -Bob Martin




   12

Sunday, February 19, 12
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


   13

Sunday, February 19, 12
Spring, a walking tour

   • Demos:
          – Bean*PostProcessor
          – AspectJ




   14

Sunday, February 19, 12
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.




   15

Sunday, February 19, 12
Scopes

   • 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

   16

Sunday, February 19, 12
Scopes
           – Implement o.s.beans.factory.config.Scope
           – register the scope with a
             o.s.beans.factory.config.CustomScopeConfigurer


   public interface Scope {

   	           Object get(String name, ObjectFactory<?> objectFactory);

   	           Object remove(String name);

   	           void registerDestructionCallback(String name, Runnable callback);

   	           Object resolveContextualObject(String key);

   	           String getConversationId();
   }




   17

Sunday, February 19, 12
Scopes
           – Implement o.s.beans.factory.config.Scope
           – register the scope with a
             o.s.beans.factory.config.CustomScopeConfigurer


   public interface Scope {

   	           Object get(String name, ObjectFactory<?> objectFactory);   map-like lookup
                                                                          of beans in a
   	           Object remove(String name);                                given scope

   	           void registerDestructionCallback(String name, Runnable callback);

   	           Object resolveContextualObject(String key);

   	           String getConversationId();
   }




   17

Sunday, February 19, 12
Scopes
           – Implement o.s.beans.factory.config.Scope
           – register the scope with a
             o.s.beans.factory.config.CustomScopeConfigurer


   public interface Scope {

   	           Object get(String name, ObjectFactory<?> objectFactory);     map-like lookup
                                                                            of beans in a
   	           Object remove(String name);                                  given scope

   	           void registerDestructionCallback(String name, Runnable callback);

   	           Object resolveContextualObject(String key);     well known beans like the
                                                               HttpServletRequest ‘request’ for
   	           String getConversationId();                     ‘request’ scope
   }




   17

Sunday, February 19, 12
Scopes
           – Implement o.s.beans.factory.config.Scope
           – register the scope with a
             o.s.beans.factory.config.CustomScopeConfigurer


   public interface Scope {

   	           Object get(String name, ObjectFactory<?> objectFactory);      map-like lookup
                                                                             of beans in a
   	           Object remove(String name);                                   given scope

   	           void registerDestructionCallback(String name, Runnable callback);

   	           Object resolveContextualObject(String key);     well known beans like the
                                                               HttpServletRequest ‘request’ for
   	           String getConversationId();                     ‘request’ scope
   }
                                                               null, or storage specific
                                                               ‘conversation’ ID


   17

Sunday, February 19, 12
Spring, a walking tour

   • Demos:
          – life cycle callbacks
          – scopes
                • using
                • creating your own




   18

Sunday, February 19, 12
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




   19

Sunday, February 19, 12
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




   20

Sunday, February 19, 12
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 = “#{ .. }”




   21

Sunday, February 19, 12
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




   22

Sunday, February 19, 12
Getting Beans from Strange Places

   • An ApplicationContextInitializer

        public interface ApplicationContextInitializer
              <C extends ConfigurableApplicationContext> {

                   void initialize(C applicationContext);
        }




   23

Sunday, February 19, 12
Getting Beans from Strange Places

   • Demos:
          – FactoryBeans
          – SpEL
          – Profiles
                • ApplicationContextInitializers




   24

Sunday, February 19, 12
Using Spring’s Resources

   • Spring supports out of the box ClassPathResource,
     FileResource system, etc.
   • Writing your own Resource implementations
              public interface Resource extends InputStreamSource {
                boolean exists();
                boolean isReadable();
                boolean isOpen();
                URL getURL() throws IOException;
                URI getURI() throws IOException;
                File getFile() throws IOException;
                long contentLength() throws IOException;
                long lastModified() throws IOException;
                Resource createRelative(String relativePath) throws IOException;
                String getFilename();
                String getDescription();
              }

   25

Sunday, February 19, 12
Object to XML Marshallers

   • Easy to add your own Marshaller (and Unmarshaller)



        public interface Marshaller {

        	         boolean supports(Class<?> clazz);

        	         void marshal(Object graph, Result result)
                      throws IOException, XmlMappingException;
        }




   26

Sunday, February 19, 12
Object to XML Marshallers

   • Demos:
          – a custom object-to-XML marshaller




   27

Sunday, February 19, 12
REST

   • Spring MVC for the server


   @RequestMapping( value = “/crm/customers/{id}” ,
                     method =HttpMethod.GET)
   public @ResponseBody Customer lookupCustomerById(
                 @PathVariable(“id”) long customerId ) {

        ...
        return customer;
   }




   28

Sunday, February 19, 12
REST

   • RestTemplate for the client (Android, SE, web
     applications, etc.)


        RestTemplate rt = new RestTemplate() ;

        String url = “http://mysvc.cloudfoundry.com/crm/customer/{id}”;

        Customer customer = rt.getForObject( url, Customer.class, 22);




   29

Sunday, February 19, 12
REST

   • Both need o.s.http.converter.HttpMessageConverters
   • Spring supports:
          –   object-to-XML (JAXB as well as any Spring OXM impl)
          –   object-to-JSON
          –   binary data (o.s.resource.Resource references or byte[])
          –   ATOM/RSS
          –   images
   • Easy to add your own




   30

Sunday, February 19, 12
Registering a custom HttpMessageConverter


        @EnableWebMvc
        public class WebConfiguration extends WebMvcConfigurerAdapter {

            @Override
            public void configureMessageConverters(
                 List<HttpMessageConverter<?>> converters) {


            }

        }




   31

Sunday, February 19, 12
REST

   • Demos:
          – Writing and using a customer HttpMessageConverter




   32

Sunday, February 19, 12
Transactions

   • Spring supports declarative transaction management
          – @EnableTransactionManagement or
            <tx:annotation-driven/>


   • PlatformTransactionManager implementations used to
     manage transactions
          – lots of options out of the box:
                • AMQP, JMS, JTA, JDBC, JDO, JPA, WebLogic-specific,
                  WebSphere-specific, OC4J-specific, etc.




   33

Sunday, February 19, 12
Transactions

   • PlatformTransactionManager abstracts the notion
     of a transactional “unit of work.”


        public interface PlatformTransactionManager {
        	
          TransactionStatus getTransaction(TransactionDefinition definition)
                   throws TransactionException;

         void commit(TransactionStatus status) throws TransactionException;

         void rollback(TransactionStatus status) throws TransactionException;
        }




   34

Sunday, February 19, 12
Caching

   • CacheManager’s maintain Caches.
          – CacheManagers are like ‘connections’
          – Caches are like regions of a cache

    public interface CacheManager {         public interface Cache {
      Cache getCache(String name);
      Collection<String> getCacheNames();    interface ValueWrapper {
    }                                          Object get();
                                            }

                                             String getName();
                                             Object getNativeCache();
                                             ValueWrapper get(Object key);
                                             void put(Object key, Object value);
                                             void evict(Object key);
                                             void clear();
                                            }

   35

Sunday, February 19, 12
Writing a custom View and View Resolver




   36

Sunday, February 19, 12
Writing a custom View and View Resolver

   • Easy to add your own View
          – supported views out of the box: FreeMarker, Velocity,
            Excel, PDFs, JasperReports, XSLT, Jackson, JSTL, etc.
          – Lots of contributions from the open source community:
                • Thymeleaf
                  http://www.thymeleaf.org/
                • Mustache by Sean Scanlon
                  https://github.com/sps/mustache-spring-view




   37

Sunday, February 19, 12
Writing a custom View and View Resolver



         public interface ViewResolver {
           View resolveViewName(String viewName, Locale locale)
               throws Exception;
         }




   38

Sunday, February 19, 12
Writing a custom View and View Resolver


public interface View {

	          String RESPONSE_STATUS_ATTRIBUTE =
                      View.class.getName() + ".responseStatus";
	
	          String getContentType();

	          void render(Map<String, ?> model,
                        HttpServletRequest request,
                        HttpServletResponse response) throws Exception;

}




    39

Sunday, February 19, 12
Writing a custom View and View Resolver

 @Bean
 public ViewResolver myCustomViewResolver(){
   ...
 }                                         if ‘detectAllViewResolvers’ is
                                                   true, all ViewResolvers types
                                                   will be registered.


   @Bean
   public MyCustomViewResolver viewResolver()
   {
      ...
    }




   40

Sunday, February 19, 12
Writing a custom View and View Resolver

 @Bean
 public ViewResolver myCustomViewResolver(){
   ...
 }                                         if ‘detectAllViewResolvers’ is
                                                    true, all ViewResolvers types
                                                    will be registered.


   @Bean
   public MyCustomViewResolver viewResolver()
   {
      ...                                   if ‘detectAllViewResolvers’ is
                                            false, it’ll lookup a bean by a
    }                                       well known name




   40

Sunday, February 19, 12
Writing a custom View and View Resolver

   • Demo: writing a custom view/view resolver




   41

Sunday, February 19, 12
Writing Adapters in Spring Integration




   42

Sunday, February 19, 12
Writing Adapters in Spring Integration

   • MessageSource for inbound adapters
   • MessageHandler for outbound adapters




    MessageSource                      MessageHandler




   43

Sunday, February 19, 12
Writing Adapters in Spring Integration

   • Inbound channel adapter “receives” message from
     external system inward relative to Spring Integration code

              package org.springframework.integration.core;

              public interface MessageSource<T> {
                org.springframework.integration.Message<T> receive();
              }

              <int:channel id = “in” />

              <int:inbound-channel-adapter
                 channel = “in” ref = “myCustomMessageSource” >
               <int:cron-trigger ... />
              </int:inbound-channel-adapter>


   44

Sunday, February 19, 12
Writing Adapters in Spring Integration

   • Outbound channel adapter “publishes” message from Spring
     Integration outward relative to Spring Integration code

              package org.springframework.integration.core;

              public interface MessageHandler {

               void handleMessage(
                  org.springframework.integration.Message<?> message)
                throws org.springframework.integration.MessagingException;

              }

              <int:channel id = “out” />

              <int:outbound-channel-adapter
                 channel = “out” ref = “myCustomMessageHandler” />

   45

Sunday, February 19, 12
Spring Integration File System Adapters

   • Spring Integration provides rich file system adapters
          – FTP, SFTP, FTPS, files in general
          – But... what about SMB/CIFS?




   46

Sunday, February 19, 12
Writing Readers and Writers in Spring Batch

   • ItemReader for inbound adapters
   • ItemWriters for outbound adapters




   47

Sunday, February 19, 12
Summary / Questions

   • code: git.springsource.org:spring-samples/spring-
     samples.git
   • blog.springsource.org
   • josh.long@springsource.com
   • springsource.com/developer/sts




   48

Sunday, February 19, 12
Q&A




 49   © 2011 SpringOne 2GX 2011. All rights reserved. Do not distribute without permission.

Sunday, February 19, 12

More Related Content

What's hot

The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update finalJoshua Long
 
Build and Deploy Sites Using Features
Build and Deploy Sites Using Features Build and Deploy Sites Using Features
Build and Deploy Sites Using Features Phase2
 
Migrating from Backgroundrb to Resque
Migrating from Backgroundrb to ResqueMigrating from Backgroundrb to Resque
Migrating from Backgroundrb to Resquekeenanbrock
 
HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.
HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.
HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.Takatoshi Matsuo
 
Log everything!
Log everything!Log everything!
Log everything!ICANS GmbH
 
Rapid JCR applications development with Sling
Rapid JCR applications development with SlingRapid JCR applications development with Sling
Rapid JCR applications development with SlingBertrand Delacretaz
 
Cloud Foundry Open Tour - London
Cloud Foundry Open Tour - LondonCloud Foundry Open Tour - London
Cloud Foundry Open Tour - Londonmarklucovsky
 

What's hot (8)

Grails 2.0 Update
Grails 2.0 UpdateGrails 2.0 Update
Grails 2.0 Update
 
The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update final
 
Build and Deploy Sites Using Features
Build and Deploy Sites Using Features Build and Deploy Sites Using Features
Build and Deploy Sites Using Features
 
Migrating from Backgroundrb to Resque
Migrating from Backgroundrb to ResqueMigrating from Backgroundrb to Resque
Migrating from Backgroundrb to Resque
 
HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.
HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.
HA Clustering of PostgreSQL(replication)@2012.9.29 PG Study.
 
Log everything!
Log everything!Log everything!
Log everything!
 
Rapid JCR applications development with Sling
Rapid JCR applications development with SlingRapid JCR applications development with Sling
Rapid JCR applications development with Sling
 
Cloud Foundry Open Tour - London
Cloud Foundry Open Tour - LondonCloud Foundry Open Tour - London
Cloud Foundry Open Tour - London
 

Viewers also liked

Enterprise Integration and Batch Processing on Cloud Foundry
Enterprise Integration and Batch Processing on Cloud FoundryEnterprise Integration and Batch Processing on Cloud Foundry
Enterprise Integration and Batch Processing on Cloud FoundryJoshua Long
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the ScenesJoshua Long
 
Spring Integration and EIP Introduction
Spring Integration and EIP IntroductionSpring Integration and EIP Introduction
Spring Integration and EIP IntroductionIwein Fuld
 
S2GX 2012 - Introduction to Spring Integration and Spring Batch
S2GX 2012 - Introduction to Spring Integration and Spring BatchS2GX 2012 - Introduction to Spring Integration and Spring Batch
S2GX 2012 - Introduction to Spring Integration and Spring BatchGunnar Hillert
 
Spring integration概要
Spring integration概要Spring integration概要
Spring integration概要kuroiwa
 
Pattern driven Enterprise Architecture
Pattern driven Enterprise ArchitecturePattern driven Enterprise Architecture
Pattern driven Enterprise ArchitectureWSO2
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Wangeun Lee
 
Economies of Scaling Software
Economies of Scaling SoftwareEconomies of Scaling Software
Economies of Scaling SoftwareJoshua Long
 
기업 통합 패턴(Enterprise Integration Patterns) 강의
기업 통합 패턴(Enterprise Integration Patterns) 강의기업 통합 패턴(Enterprise Integration Patterns) 강의
기업 통합 패턴(Enterprise Integration Patterns) 강의정호 차
 

Viewers also liked (10)

The Spring Update
The Spring UpdateThe Spring Update
The Spring Update
 
Enterprise Integration and Batch Processing on Cloud Foundry
Enterprise Integration and Batch Processing on Cloud FoundryEnterprise Integration and Batch Processing on Cloud Foundry
Enterprise Integration and Batch Processing on Cloud Foundry
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the Scenes
 
Spring Integration and EIP Introduction
Spring Integration and EIP IntroductionSpring Integration and EIP Introduction
Spring Integration and EIP Introduction
 
S2GX 2012 - Introduction to Spring Integration and Spring Batch
S2GX 2012 - Introduction to Spring Integration and Spring BatchS2GX 2012 - Introduction to Spring Integration and Spring Batch
S2GX 2012 - Introduction to Spring Integration and Spring Batch
 
Spring integration概要
Spring integration概要Spring integration概要
Spring integration概要
 
Pattern driven Enterprise Architecture
Pattern driven Enterprise ArchitecturePattern driven Enterprise Architecture
Pattern driven Enterprise Architecture
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계
 
Economies of Scaling Software
Economies of Scaling SoftwareEconomies of Scaling Software
Economies of Scaling Software
 
기업 통합 패턴(Enterprise Integration Patterns) 강의
기업 통합 패턴(Enterprise Integration Patterns) 강의기업 통합 패턴(Enterprise Integration Patterns) 강의
기업 통합 패턴(Enterprise Integration Patterns) 강의
 

Similar to Extending Spring for Custom Usage

Extending spring
Extending springExtending spring
Extending springJoshua Long
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundryJoshua Long
 
CloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heavenCloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heavenPatrick Chanezon
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud FoundryJoshua Long
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Leejaxconf
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repositorynobby
 
A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom Joshua Long
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Rittercatherinewall
 
Plone FSR
Plone FSRPlone FSR
Plone FSRfulv
 
MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataChris Richardson
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
Cloud Best Practices
Cloud Best PracticesCloud Best Practices
Cloud Best PracticesEric Bottard
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
Building Next-Gen Web Applications with the Spring 3 Web Stack
Building Next-Gen Web Applications with the Spring 3 Web StackBuilding Next-Gen Web Applications with the Spring 3 Web Stack
Building Next-Gen Web Applications with the Spring 3 Web StackJeremy Grelle
 
Real World Application Performance with MongoDB
Real World Application Performance with MongoDBReal World Application Performance with MongoDB
Real World Application Performance with MongoDBMongoDB
 

Similar to Extending Spring for Custom Usage (20)

Extending spring
Extending springExtending spring
Extending spring
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud Foundry
 
CloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heavenCloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heaven
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundry
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Lee
 
Lo nuevo en Spring 3.0
Lo nuevo  en Spring 3.0Lo nuevo  en Spring 3.0
Lo nuevo en Spring 3.0
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repository
 
Play framework
Play frameworkPlay framework
Play framework
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
Plone FSR
Plone FSRPlone FSR
Plone FSR
 
MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring Data
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Cloud Best Practices
Cloud Best PracticesCloud Best Practices
Cloud Best Practices
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Building Next-Gen Web Applications with the Spring 3 Web Stack
Building Next-Gen Web Applications with the Spring 3 Web StackBuilding Next-Gen Web Applications with the Spring 3 Web Stack
Building Next-Gen Web Applications with the Spring 3 Web Stack
 
Real World Application Performance with MongoDB
Real World Application Performance with MongoDBReal World Application Performance with MongoDB
Real World Application Performance with MongoDB
 

More from Joshua Long

Bootiful Code with Spring Boot
Bootiful Code with Spring BootBootiful Code with Spring Boot
Bootiful Code with Spring BootJoshua Long
 
Microservices with Spring Boot
Microservices with Spring BootMicroservices with Spring Boot
Microservices with Spring BootJoshua Long
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?Joshua Long
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013Joshua Long
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Integration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryIntegration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryJoshua Long
 
Spring in-the-cloud
Spring in-the-cloudSpring in-the-cloud
Spring in-the-cloudJoshua Long
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeThe Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeJoshua Long
 
Multi client Development with Spring
Multi client Development with SpringMulti client Development with Spring
Multi client Development with SpringJoshua Long
 
Cloud Foundry Bootcamp
Cloud Foundry BootcampCloud Foundry Bootcamp
Cloud Foundry BootcampJoshua Long
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenJoshua Long
 
Using Spring's IOC Model
Using Spring's IOC ModelUsing Spring's IOC Model
Using Spring's IOC ModelJoshua Long
 
a Running Tour of Cloud Foundry
a Running Tour of Cloud Foundrya Running Tour of Cloud Foundry
a Running Tour of Cloud FoundryJoshua Long
 
Cloud Foundry, Spring and Vaadin
Cloud Foundry, Spring and VaadinCloud Foundry, Spring and Vaadin
Cloud Foundry, Spring and VaadinJoshua Long
 

More from Joshua Long (20)

Bootiful Code with Spring Boot
Bootiful Code with Spring BootBootiful Code with Spring Boot
Bootiful Code with Spring Boot
 
Microservices with Spring Boot
Microservices with Spring BootMicroservices with Spring Boot
Microservices with Spring Boot
 
Boot It Up
Boot It UpBoot It Up
Boot It Up
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Integration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryIntegration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud Foundry
 
Spring in-the-cloud
Spring in-the-cloudSpring in-the-cloud
Spring in-the-cloud
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeThe Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
 
Multi client Development with Spring
Multi client Development with SpringMulti client Development with Spring
Multi client Development with Spring
 
Cloud Foundry Bootcamp
Cloud Foundry BootcampCloud Foundry Bootcamp
Cloud Foundry Bootcamp
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Using Spring's IOC Model
Using Spring's IOC ModelUsing Spring's IOC Model
Using Spring's IOC Model
 
a Running Tour of Cloud Foundry
a Running Tour of Cloud Foundrya Running Tour of Cloud Foundry
a Running Tour of Cloud Foundry
 
Cloud Foundry, Spring and Vaadin
Cloud Foundry, Spring and VaadinCloud Foundry, Spring and Vaadin
Cloud Foundry, Spring and Vaadin
 

Recently uploaded

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

Extending Spring for Custom Usage

  • 1. Tailoring Spring for Custom Usage • Josh Long, SpringSource, a division of VMware 1 Sunday, February 19, 12
  • 2. About Josh Long (Spring Developer Advocate) @starbuxman josh.long@springsource.com th s i is im po rta nt ! 2 Sunday, February 19, 12
  • 3. Agenda Explore the value of a framework Exploit some of the lesser known, but powerful, extension hooks in the core Spring framework QA 3 Sunday, February 19, 12
  • 4. Spring’s aim: bring simplicity to java development data web tier integration batch access & service tier & mobile processing / NoSQL / RIA messaging Big Data The Spring framework the cloud: lightweight traditional CloudFoundry WebSphere tc Server VMForce JBoss AS Tomcat Google App Engine WebLogic Jetty Amazon Web Services (on legacy versions, too!) 4 Sunday, February 19, 12
  • 5. 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 5 Sunday, February 19, 12
  • 6. 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 6 Sunday, February 19, 12
  • 7. Spring Integration rules!! Not confidential. Tell everyone. 7 Sunday, February 19, 12
  • 8. ...but??!? ...what if it doesn’t do what I want? 8 Sunday, February 19, 12
  • 9. What is Spring Integration? FLEXIBLE v Not confidential. Tell everyone. 9 Sunday, February 19, 12
  • 11. do NOT reinvent the Wheel! 11 Sunday, February 19, 12
  • 12. The Open/Closed Principle "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification” -Bob Martin 12 Sunday, February 19, 12
  • 13. 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 13 Sunday, February 19, 12
  • 14. Spring, a walking tour • Demos: – Bean*PostProcessor – AspectJ 14 Sunday, February 19, 12
  • 15. 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. 15 Sunday, February 19, 12
  • 16. Scopes • 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 16 Sunday, February 19, 12
  • 17. Scopes – Implement o.s.beans.factory.config.Scope – register the scope with a o.s.beans.factory.config.CustomScopeConfigurer public interface Scope { Object get(String name, ObjectFactory<?> objectFactory); Object remove(String name); void registerDestructionCallback(String name, Runnable callback); Object resolveContextualObject(String key); String getConversationId(); } 17 Sunday, February 19, 12
  • 18. Scopes – Implement o.s.beans.factory.config.Scope – register the scope with a o.s.beans.factory.config.CustomScopeConfigurer public interface Scope { Object get(String name, ObjectFactory<?> objectFactory); map-like lookup of beans in a Object remove(String name); given scope void registerDestructionCallback(String name, Runnable callback); Object resolveContextualObject(String key); String getConversationId(); } 17 Sunday, February 19, 12
  • 19. Scopes – Implement o.s.beans.factory.config.Scope – register the scope with a o.s.beans.factory.config.CustomScopeConfigurer public interface Scope { Object get(String name, ObjectFactory<?> objectFactory); map-like lookup of beans in a Object remove(String name); given scope void registerDestructionCallback(String name, Runnable callback); Object resolveContextualObject(String key); well known beans like the HttpServletRequest ‘request’ for String getConversationId(); ‘request’ scope } 17 Sunday, February 19, 12
  • 20. Scopes – Implement o.s.beans.factory.config.Scope – register the scope with a o.s.beans.factory.config.CustomScopeConfigurer public interface Scope { Object get(String name, ObjectFactory<?> objectFactory); map-like lookup of beans in a Object remove(String name); given scope void registerDestructionCallback(String name, Runnable callback); Object resolveContextualObject(String key); well known beans like the HttpServletRequest ‘request’ for String getConversationId(); ‘request’ scope } null, or storage specific ‘conversation’ ID 17 Sunday, February 19, 12
  • 21. Spring, a walking tour • Demos: – life cycle callbacks – scopes • using • creating your own 18 Sunday, February 19, 12
  • 22. 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 19 Sunday, February 19, 12
  • 23. 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 20 Sunday, February 19, 12
  • 24. 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 = “#{ .. }” 21 Sunday, February 19, 12
  • 25. 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 22 Sunday, February 19, 12
  • 26. Getting Beans from Strange Places • An ApplicationContextInitializer public interface ApplicationContextInitializer <C extends ConfigurableApplicationContext> { void initialize(C applicationContext); } 23 Sunday, February 19, 12
  • 27. Getting Beans from Strange Places • Demos: – FactoryBeans – SpEL – Profiles • ApplicationContextInitializers 24 Sunday, February 19, 12
  • 28. Using Spring’s Resources • Spring supports out of the box ClassPathResource, FileResource system, etc. • Writing your own Resource implementations public interface Resource extends InputStreamSource { boolean exists(); boolean isReadable(); boolean isOpen(); URL getURL() throws IOException; URI getURI() throws IOException; File getFile() throws IOException; long contentLength() throws IOException; long lastModified() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); } 25 Sunday, February 19, 12
  • 29. Object to XML Marshallers • Easy to add your own Marshaller (and Unmarshaller) public interface Marshaller { boolean supports(Class<?> clazz); void marshal(Object graph, Result result) throws IOException, XmlMappingException; } 26 Sunday, February 19, 12
  • 30. Object to XML Marshallers • Demos: – a custom object-to-XML marshaller 27 Sunday, February 19, 12
  • 31. REST • Spring MVC for the server @RequestMapping( value = “/crm/customers/{id}” , method =HttpMethod.GET) public @ResponseBody Customer lookupCustomerById( @PathVariable(“id”) long customerId ) { ... return customer; } 28 Sunday, February 19, 12
  • 32. REST • RestTemplate for the client (Android, SE, web applications, etc.) RestTemplate rt = new RestTemplate() ; String url = “http://mysvc.cloudfoundry.com/crm/customer/{id}”; Customer customer = rt.getForObject( url, Customer.class, 22); 29 Sunday, February 19, 12
  • 33. REST • Both need o.s.http.converter.HttpMessageConverters • Spring supports: – object-to-XML (JAXB as well as any Spring OXM impl) – object-to-JSON – binary data (o.s.resource.Resource references or byte[]) – ATOM/RSS – images • Easy to add your own 30 Sunday, February 19, 12
  • 34. Registering a custom HttpMessageConverter @EnableWebMvc public class WebConfiguration extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { } } 31 Sunday, February 19, 12
  • 35. REST • Demos: – Writing and using a customer HttpMessageConverter 32 Sunday, February 19, 12
  • 36. Transactions • Spring supports declarative transaction management – @EnableTransactionManagement or <tx:annotation-driven/> • PlatformTransactionManager implementations used to manage transactions – lots of options out of the box: • AMQP, JMS, JTA, JDBC, JDO, JPA, WebLogic-specific, WebSphere-specific, OC4J-specific, etc. 33 Sunday, February 19, 12
  • 37. Transactions • PlatformTransactionManager abstracts the notion of a transactional “unit of work.” public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; } 34 Sunday, February 19, 12
  • 38. Caching • CacheManager’s maintain Caches. – CacheManagers are like ‘connections’ – Caches are like regions of a cache public interface CacheManager { public interface Cache { Cache getCache(String name); Collection<String> getCacheNames(); interface ValueWrapper { } Object get(); } String getName(); Object getNativeCache(); ValueWrapper get(Object key); void put(Object key, Object value); void evict(Object key); void clear(); } 35 Sunday, February 19, 12
  • 39. Writing a custom View and View Resolver 36 Sunday, February 19, 12
  • 40. Writing a custom View and View Resolver • Easy to add your own View – supported views out of the box: FreeMarker, Velocity, Excel, PDFs, JasperReports, XSLT, Jackson, JSTL, etc. – Lots of contributions from the open source community: • Thymeleaf http://www.thymeleaf.org/ • Mustache by Sean Scanlon https://github.com/sps/mustache-spring-view 37 Sunday, February 19, 12
  • 41. Writing a custom View and View Resolver public interface ViewResolver { View resolveViewName(String viewName, Locale locale) throws Exception; } 38 Sunday, February 19, 12
  • 42. Writing a custom View and View Resolver public interface View { String RESPONSE_STATUS_ATTRIBUTE = View.class.getName() + ".responseStatus"; String getContentType(); void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception; } 39 Sunday, February 19, 12
  • 43. Writing a custom View and View Resolver @Bean public ViewResolver myCustomViewResolver(){ ... } if ‘detectAllViewResolvers’ is true, all ViewResolvers types will be registered. @Bean public MyCustomViewResolver viewResolver() { ... } 40 Sunday, February 19, 12
  • 44. Writing a custom View and View Resolver @Bean public ViewResolver myCustomViewResolver(){ ... } if ‘detectAllViewResolvers’ is true, all ViewResolvers types will be registered. @Bean public MyCustomViewResolver viewResolver() { ... if ‘detectAllViewResolvers’ is false, it’ll lookup a bean by a } well known name 40 Sunday, February 19, 12
  • 45. Writing a custom View and View Resolver • Demo: writing a custom view/view resolver 41 Sunday, February 19, 12
  • 46. Writing Adapters in Spring Integration 42 Sunday, February 19, 12
  • 47. Writing Adapters in Spring Integration • MessageSource for inbound adapters • MessageHandler for outbound adapters MessageSource MessageHandler 43 Sunday, February 19, 12
  • 48. Writing Adapters in Spring Integration • Inbound channel adapter “receives” message from external system inward relative to Spring Integration code package org.springframework.integration.core; public interface MessageSource<T> { org.springframework.integration.Message<T> receive(); } <int:channel id = “in” /> <int:inbound-channel-adapter channel = “in” ref = “myCustomMessageSource” > <int:cron-trigger ... /> </int:inbound-channel-adapter> 44 Sunday, February 19, 12
  • 49. Writing Adapters in Spring Integration • Outbound channel adapter “publishes” message from Spring Integration outward relative to Spring Integration code package org.springframework.integration.core; public interface MessageHandler { void handleMessage( org.springframework.integration.Message<?> message) throws org.springframework.integration.MessagingException; } <int:channel id = “out” /> <int:outbound-channel-adapter channel = “out” ref = “myCustomMessageHandler” /> 45 Sunday, February 19, 12
  • 50. Spring Integration File System Adapters • Spring Integration provides rich file system adapters – FTP, SFTP, FTPS, files in general – But... what about SMB/CIFS? 46 Sunday, February 19, 12
  • 51. Writing Readers and Writers in Spring Batch • ItemReader for inbound adapters • ItemWriters for outbound adapters 47 Sunday, February 19, 12
  • 52. Summary / Questions • code: git.springsource.org:spring-samples/spring- samples.git • blog.springsource.org • josh.long@springsource.com • springsource.com/developer/sts 48 Sunday, February 19, 12
  • 53. Q&A 49 © 2011 SpringOne 2GX 2011. All rights reserved. Do not distribute without permission. Sunday, February 19, 12