Click here to load reader

Extending spring

  • View
    820

  • Download
    3

Embed Size (px)

Text of Extending spring

  • 1. Tailoring Spring for Custom Usage Josh Long, SpringSource, a division of VMware 1Thursday, January 24, 13

2. About Josh Long () Spring Developer Advocate twitter: @starbuxman weibo: @springsource [email protected], January 24, 13 3. Agenda Explore the value of a framework Exploit some of the lesser known, but powerful, extension hooks in the core Spring framework QA 3Thursday, January 24, 13 4. Springs aim:bring simplicity to java developmentdataweb tier integration batch access& service tier& mobileprocessing / NoSQL / RIA messaging Big Data The Spring framework the cloud:lightweighttraditionalCloudFoundryWebSphere tc ServerVMForceJBoss ASTomcatGoogle App Engine WebLogicJetty Amazon Web Services(on legacy versions, too!) 4Thursday, January 24, 13 5. The Spring ApplicationContext Spring Manages the beans you tell it to manage use annotations (JSR 250, JSR 330, native) XML Java conguration component scanning You can of course use all of them! Mix n match All conguration styles tell the ApplicationContext how to manage your beans 5Thursday, January 24, 13 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 conguration 6Thursday, January 24, 13 7. Spring Integration rules!! Not confidential. Tell everyone. 7Thursday, January 24, 13 8. ...but??!? ...what if it doesnt do what I want? 8Thursday, January 24, 13 9. What is Spring Integration?FLEXIBLEv Not confidential. Tell everyone. 9Thursday, January 24, 13 10. 10Thursday, January 24, 13 11. do NOT reinvent the Wheel! 11Thursday, January 24, 13 12. The Open/Closed Principle "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modication-Bob Martin 12Thursday, January 24, 13 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 congured beans havebeen created, but before the context is nished setting up BeanFactoryPostProcessor is run before any of the beans denitions are realized comes before BPP A more natural alternative is Springs AOP support built on top of AspectJ provides a very convenient, powerful way to solve crosscutting problems 13Thursday, January 24, 13 14. Spring, a walking tour Demos: Bean*PostProcessor AspectJ 14Thursday, January 24, 13 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 acertain order as well as to query whether the beans beenstarted or not. 15Thursday, January 24, 13 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 ow scoped Spring Web Flow conversation scoped Spring Web Flow view scoped (in JSF) Activiti BPMN2 process-scoped 16Thursday, January 24, 13 17. Scopes Implement o.s.beans.factory.cong.Scope register the scope with a o.s.beans.factory.cong.CustomScopeCongurer 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(); } 17Thursday, January 24, 13 18. Scopes Implement o.s.beans.factory.cong.Scope register the scope with a o.s.beans.factory.cong.CustomScopeCongurer public interface Scope { Object get(String name, ObjectFactory objectFactory); map-like lookupof beans in a Object remove(String name);given scope void registerDestructionCallback(String name, Runnable callback); Object resolveContextualObject(String key); String getConversationId(); } 17Thursday, January 24, 13 19. Scopes Implement o.s.beans.factory.cong.Scope register the scope with a o.s.beans.factory.cong.CustomScopeCongurer public interface Scope { Object get(String name, ObjectFactory objectFactory); map-like lookupof 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 } 17Thursday, January 24, 13 20. Scopes Implement o.s.beans.factory.cong.Scope register the scope with a o.s.beans.factory.cong.CustomScopeCongurer 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 17Thursday, January 24, 13 21. Spring, a walking tour Demos: life cycle callbacks scopes using creating your own 18Thursday, January 24, 13 22. Getting Beans from Strange Places FactoryBeans Spring Expression Language convenient way to get at values and inject them Spring environment specic beans (proles) introduced in Spring 3.1 make it easy to conditionally dene an object based onsome sort of runtime condition 19Thursday, January 24, 13 23. Getting Beans from Strange Places FactoryBeans interface thats used to provide a reusable denition of howto create a complicated object with many dependencies Related: Java conguration, and builders prefer both over FactoryBeans where possible 20Thursday, January 24, 13 24. Getting Beans from Strange Places Spring Expression Language convenient way to get at values and inject them Andy Clements a genius like the Unied JSF EL, on steroids Can be used in Java, XML @Value(#{ ... }) or value = #{ .. } 21Thursday, January 24, 13 25. Getting Beans from Strange Places Spring proles @Prole(production) @Conguration ... ... Use System properties or simply specify the active prole onthe environment Use ApplicationContextInitializer in web applications 22Thursday, January 24, 13 26. Getting Beans from Strange Places An ApplicationContextInitializerpublic interface ApplicationContextInitializer { void initialize(C applicationContext);} 23Thursday, January 24, 13 27. Getting Beans from Strange Places Demos: FactoryBeans SpEL Proles ApplicationContextInitializers 24Thursday, January 24, 13 28. Proxies! CustomerService cs = new CustomerService(); cs... ProxyFactory pf = new ProxyFaxctory(); pf.setTarget( cs ); pf.addAdvice(new MethodInterceptor(){ public Object invoke(MethodInvocation mi) {// ... } } ); return (CustomerService) pf.getObject() ; 25Thursday, January 24, 13 29. Using Springs 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 lastModied() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); } 26Thursday, January 24, 13 30. 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;} 27Thursday, January 24, 13 31. Object to XML Marshallers Demos: a custom object-to-XML marshaller 28Thursday, January 24, 13 32. REST Spring MVC for the server @RequestMapping( value = /crm/customers/{id} , method =HttpMethod.GET) public @ResponseBody Customer lookupCustomerById( @PathVariable(id) long customerId ) {...return customer; } 29Thursday, January 24, 13 33. 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); 30Thursday, January 24, 13 34. 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 31Thursday, January 24, 13 35. Registering a custom [email protected] class WebConguration extends WebMvcCongurerAdapter {@Overridepublic void congureMessageConverters( List> converters) {}} 32Thursday, January 24, 13 36. REST Demos: Writing and using a customer HttpMessageConverter 33Thursday, January 24, 13 37. Transactions Spring supports declarative transaction management @EnableTransactionManagement or PlatformTransactionManager implementations used to manage transactions lots of options out of the box: AMQP, JMS, JTA, JDBC, JDO, JPA, WebLogic-specic,WebSphere-specic, OC4J-specic, etc. 34Thursday, January 24, 13 38. Transactions PlatformTransactionManager abstracts the notion of a transactional unit of work.public interface PlatformTransactionManager {TransactionStatus getTransaction(TransactionDenition denition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException;} 35Thursday, January 24, 13 39. Caching CacheManagers maintain Caches. CacheManagers are like connections Caches are like regions of a cachepublic interface CacheManager { public interface Cache {Cache g

Search related