SlideShare a Scribd company logo
Under the Hood:
Using Spring in Grails
    Burt Beckwith
     SpringSource
Who Am I




  CONFIDENTIAL   2
Who Am I


 Java developer for over 13 years

 Background in Spring, Hibernate, Spring Security

 Grails developer for 5 years

 SpringSource employee on the Grails team

 Created or reworked over 40 Grails plugins

 http://burtbeckwith.com/blog/

 https://twitter.com/#!/burtbeckwith
                         CONFIDENTIAL               3
Spring Overview
 Main functions of Spring
 • Bean container: ApplicationContext and BeanFactory
 • Dependency Injection (DI) and Inversion of Control (IoC)
 • Proxies
   • Transactions
   • Security
   • Caching
 • Event publishing and listening
 • Exception conversion
                             CONFIDENTIAL                     4
Bean PostProcessors




        CONFIDENTIAL   5
Bean PostProcessors


 o.s.b.factory.config.BeanPostProcessor
 • Object postProcessBeforeInitialization(Object bean, 

  String beanName)

 • Object postProcessAfterInitialization(Object bean, 

  String beanName)




                           CONFIDENTIAL                   6
Bean PostProcessors


 o.s.b.factory.config.BeanFactoryPostProcessor
 • void postProcessBeanFactory(ConfigurableListableBeanFactory 

  beanFactory)




                            CONFIDENTIAL                      7
Bean PostProcessors


 o.s.b.factory.support.BeanDefinitionRegistryPostProcessor
 • extends BeanFactoryPostProcessor

 • void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry 

  registry)




                                 CONFIDENTIAL                       8
Cloud Support Plugin (cloud­foundry, heroku)




   dataSourceBean.driverClassName = 
   updatedValues.driverClassName

   dataSourceBean.url = updatedValues.url + suffix

   dataSourceBean.username = updatedValues.userName

   dataSourceBean.password = updatedValues.password




                             CONFIDENTIAL             9
Alternate approach to BeanDefinition modification




  def doWithSpring = {

     def mybeanDef = delegate.getBeanDefinition('mybean')

     mybeanDef.beanClass = NewClass

     mybeanDef.propertyValues.add("order",
           application.config.plugin?.rendering?.order ?: 42)
  }



  ●   Use loadAfter = ['plugin1', 'plugin2'] to
  ensure the bean is loaded
  ●   Only valid in a plugin, not the app's resources.groovy
                               CONFIDENTIAL                    10
Bean Aliases




   CONFIDENTIAL   11
Aliases


 As of Grails 2.1 aliases work fully

 • You can create aliases pre­2.1 but only if defined in the same 

  resources.groovy or plugin (doWithSpring)


   beans = {
      springConfig.addAlias 'alias', 'realBean'
   }




                              CONFIDENTIAL                       12
Aliases


 The cache plugin registers the alias cacheOperationSource for 

 the bean registered as 
 org.springframework.cache.annotation.AnnotationCacheOperationSource#0



 Can use to have multiple implementations of a bean and choose 

 one via configuration at startup, e.g. per­environment or some 

 other rule




                                 CONFIDENTIAL                            13
Spring MVC Controllers




         CONFIDENTIAL    14
Spring MVC


 New in Grails 1.2

 Annotate src/java or src/groovy classes with @Controller

 Add all packages to the grails.spring.bean.packages list in

 Config.groovy

 • e.g.grails.spring.bean.packages = ['gr8conf.testapp.foo']




                            CONFIDENTIAL                        15
Spring MVC


 Annotate methods with
 @o.s.w.bind.annotation.RequestMapping



   @RequestMapping("/mvc/hello.dispatch")
   public ModelMap handleRequest() {
      return new ModelMap()
         .addAttribute("text", "some text")
         .addAttribute("cost", 42)
         .addAttribute("config",
             grailsApplication.getConfig().flatten()));
   }




                          CONFIDENTIAL                    16
Spring MVC


 @RequestMapping URI value must end in .dispatch
 Add entries in UrlMappings to create more natural URLs

   class UrlMappings {

      static mappings = {
         …

         "/mvc/hello"(uri:"/mvc/hello.dispatch")

         "/mvc/other"(uri:"/mvc/other.dispatch")
      }
   }



                              CONFIDENTIAL                 17
Spring MVC


 Use @Autowired for dependency injection (on fields in Groovy 
 classes, on setters or constructors in Java)


   private GrailsApplication grailsApplication;

   @Autowired
   public void setGrailsApplication(GrailsApplication app) {
      grailsApplication = app;
   }




                                 CONFIDENTIAL                     18
Transactions




   CONFIDENTIAL   19
Utility Methods




  import o.s.t.interceptor.TransactionAspectSupport
  import o.s.t.support.TransactionSynchronizationManager

  for (sc in grailsApplication.serviceClasses) {
     def metaClass = sc.clazz.metaClass

     …
  }




                           CONFIDENTIAL                    20
Utility Methods




  // returns TransactionStatus
  metaClass.getCurrentTransactionStatus = { ­>
     if (!delegate.isTransactionActive()) {
         return null
     }
     TransactionAspectSupport.currentTransactionStatus()
  }




                           CONFIDENTIAL                    21
Utility Methods




  // void, throws NoTransactionException
  metaClass.setRollbackOnly = { ­>
     TransactionAspectSupport.currentTransactionStatus()
           .setRollbackOnly()
  }




                           CONFIDENTIAL                    22
Utility Methods




  // returns boolean
  metaClass.isRollbackOnly = { ­>
     if (!delegate.isTransactionActive()) {
         return false
     }
     delegate.getCurrentTransactionStatus().isRollbackOnly()
  }




                           CONFIDENTIAL                        23
Utility Methods




  // returns boolean
  metaClass.isTransactionActive = { ­>
     TransactionSynchronizationManager
           .isSynchronizationActive()
  }




                           CONFIDENTIAL   24
Proxies




 CONFIDENTIAL   25
A Simple Proxied Bean – The interface



     package gr8conf.eu.spring;

     public interface ThingManager {

         void method1();

         int methodTwo(boolean foo);
     }




                             CONFIDENTIAL   26
A Simple Proxied Bean – The implementation



     package gr8conf.eu.spring;

     public class ThingManagerImpl
            implements ThingManager {

         public void method1() {
            System.out.println("You called method1");
         }

         public int methodTwo(boolean foo) {
            System.out.println("You called methodTwo");
            return 42;
         }
     }




                            CONFIDENTIAL                  27
A Simple Proxied Bean – The FactoryBean

     package gr8conf.eu.spring;

     public class ThingManagerProxyFactoryBean
            implements FactoryBean<ThingManager>,
                       InitializingBean {

        private ThingManager managerProxy;
        private ThingManager target;

        public ThingManager getObject() {
           return managerProxy;
        }

        public Class<ThingManager> getObjectType() {
           return ThingManager.class;
        }

        public boolean isSingleton() {
           return true;
        }
                            CONFIDENTIAL               28
A Simple Proxied Bean – The FactoryBean

     public void setTarget(ThingManager manager) {
        target = manager;
     }

     public void afterPropertiesSet() {

        Assert.notNull(target,
            "The proxied manager must be set");

        Class<?>[] interfaces = { ThingManager.class };

        InvocationHandler invocationHandler =
           new InvocationHandler() {
              public Object invoke(Object proxy,
                 Method m, Object[] args)
                    throws Throwable {




                            CONFIDENTIAL                  29
A Simple Proxied Bean – The FactoryBean

              System.out.println("Before invoke " +
                                 m.getName());

              Object value = m.invoke(target, args);

              System.out.println("After invoke " +
                                 m.getName());

              return value;
           }
        };

        managerProxy = (ThingManager)Proxy.newProxyInstance(
           ThingManager.class.getClassLoader(),
           interfaces,
           invocationHandler);
        }
     }



                              CONFIDENTIAL                     30
A Simple Proxied Bean – resources.groovy

     import gr8conf.eu.spring.ThingManager
     import gr8conf.eu.spring.ThingManagerImpl
     import gr8conf.eu.spring.ThingManagerProxyFactoryBean

     beans = {

        realThingManager(ThingManagerImpl) {
           // properties, etc.
        }

        thingManager(ThingManagerProxyFactoryBean) { bean ­>
           // bean.scope = ...
           // bean.lazyInit = true
           // target = ref('realThingManager')
        }
     }




                            CONFIDENTIAL                       31
A Simple Proxied Bean – resources.groovy

     import gr8conf.eu.spring.ThingManager
     import gr8conf.eu.spring.ThingManagerImpl
     import gr8conf.eu.spring.ThingManagerProxyFactoryBean

     beans = {

        thingManager(ThingManagerProxyFactoryBean) { bean ­>
           // bean.scope = ...
           // bean.lazyInit = true

           target = { ThingManagerImpl thing ­>
              // properties, etc.
           }
        }
     }




                            CONFIDENTIAL                       32
Want More Information?




         CONFIDENTIAL    33
Under the Hood: Using Spring in Grails
Thank You




  CONFIDENTIAL   35

More Related Content

PDF
Under the Hood: Using Spring in Grails
PDF
Enterprise Guice 20090217 Bejug
PDF
Making the most of your gradle build - Greach 2017
PDF
Making the most of your gradle build - Gr8Conf 2017
PDF
Testing Java Code Effectively
PPTX
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
PDF
Intro to Retrofit 2 and RxJava2
PDF
Testing Android apps based on Dagger and RxJava
Under the Hood: Using Spring in Grails
Enterprise Guice 20090217 Bejug
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Gr8Conf 2017
Testing Java Code Effectively
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
Intro to Retrofit 2 and RxJava2
Testing Android apps based on Dagger and RxJava

What's hot (19)

PDF
Advanced Dagger talk from 360andev
PDF
Springを用いた社内ライブラリ開発
PDF
Testing Android apps based on Dagger and RxJava Droidcon UK
PDF
A portlet-API based approach for application integration
PDF
Managing user's data with Spring Session
PDF
Practical Protocol-Oriented-Programming
PDF
My way to clean android v2 English DroidCon Spain
PPTX
Making React Native UI Components with Swift
PDF
Dagger 2. Right way to do Dependency Injection
PPTX
Dagger 2. The Right Way to Dependency Injections
PDF
My way to clean android - Android day salamanca edition
PDF
Making the Most of Your Gradle Build
PDF
React lecture
PPTX
Open sourcing the store
PDF
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
PDF
The JavaFX Ecosystem
PDF
Android development
PDF
Java Libraries You Can’t Afford to Miss
PPTX
Java Libraries You Can’t Afford to Miss
Advanced Dagger talk from 360andev
Springを用いた社内ライブラリ開発
Testing Android apps based on Dagger and RxJava Droidcon UK
A portlet-API based approach for application integration
Managing user's data with Spring Session
Practical Protocol-Oriented-Programming
My way to clean android v2 English DroidCon Spain
Making React Native UI Components with Swift
Dagger 2. Right way to do Dependency Injection
Dagger 2. The Right Way to Dependency Injections
My way to clean android - Android day salamanca edition
Making the Most of Your Gradle Build
React lecture
Open sourcing the store
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
The JavaFX Ecosystem
Android development
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
Ad

Similar to Under the Hood: Using Spring in Grails (20)

PDF
GR8Conf 2011: Grails, how to plug in
PDF
Grails Plugin Best Practices
PDF
Spring design-juergen-qcon
PDF
Grails Integration Strategies
PDF
Hacking the Grails Spring Security Plugins
PPTX
Spring Northwest Usergroup Grails Presentation
PDF
Greach 2014 - Road to Grails 3.0
KEY
Groovy: to Infinity and Beyond -- JavaOne 2010 -- Guillaume Laforge
PPT
Spring, web service, web server, eclipse by a introduction sandesh sharma
PDF
Spring Cairngorm
PDF
BlazeDS
PPTX
Grails Advanced
PDF
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
PDF
Grails 101
ODP
Testing the Grails Spring Security Plugins
PDF
GR8Conf 2011: GORM Optimization
PDF
Getting Started With Spring Framework J Sharma Ashish Sarin
PPTX
SAP Inside Track Singapore 2014
PDF
Hacking the Grails Spring Security 2.0 Plugin
PDF
G*ワークショップ in 仙台 Grails(とことん)入門
GR8Conf 2011: Grails, how to plug in
Grails Plugin Best Practices
Spring design-juergen-qcon
Grails Integration Strategies
Hacking the Grails Spring Security Plugins
Spring Northwest Usergroup Grails Presentation
Greach 2014 - Road to Grails 3.0
Groovy: to Infinity and Beyond -- JavaOne 2010 -- Guillaume Laforge
Spring, web service, web server, eclipse by a introduction sandesh sharma
Spring Cairngorm
BlazeDS
Grails Advanced
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
Grails 101
Testing the Grails Spring Security Plugins
GR8Conf 2011: GORM Optimization
Getting Started With Spring Framework J Sharma Ashish Sarin
SAP Inside Track Singapore 2014
Hacking the Grails Spring Security 2.0 Plugin
G*ワークショップ in 仙台 Grails(とことん)入門
Ad

More from GR8Conf (20)

PDF
DevOps Enabling Your Team
PDF
Creating and testing REST contracts with Accurest Gradle
PDF
Mum, I want to be a Groovy full-stack developer
PDF
Metaprogramming with Groovy
PDF
Scraping with Geb
PDF
How to create a conference android app with Groovy and Android
PDF
Ratpack On the Docks
PDF
Groovy Powered Clean Code
PDF
Cut your Grails application to pieces - build feature plugins
PDF
Performance tuning Grails applications
PDF
Ratpack and Grails 3
PDF
Grails & DevOps: continuous integration and delivery in the cloud
PDF
Functional testing your Grails app with GEB
PDF
Deploying, Scaling, and Running Grails on AWS and VPC
PDF
The Grails introduction workshop
PDF
Idiomatic spock
PDF
The Groovy Ecosystem Revisited
PDF
Groovy 3 and the new Groovy Meta Object Protocol in examples
PDF
Integration using Apache Camel and Groovy
PDF
CRaSH the shell for the Java Virtual Machine
DevOps Enabling Your Team
Creating and testing REST contracts with Accurest Gradle
Mum, I want to be a Groovy full-stack developer
Metaprogramming with Groovy
Scraping with Geb
How to create a conference android app with Groovy and Android
Ratpack On the Docks
Groovy Powered Clean Code
Cut your Grails application to pieces - build feature plugins
Performance tuning Grails applications
Ratpack and Grails 3
Grails & DevOps: continuous integration and delivery in the cloud
Functional testing your Grails app with GEB
Deploying, Scaling, and Running Grails on AWS and VPC
The Grails introduction workshop
Idiomatic spock
The Groovy Ecosystem Revisited
Groovy 3 and the new Groovy Meta Object Protocol in examples
Integration using Apache Camel and Groovy
CRaSH the shell for the Java Virtual Machine

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Encapsulation theory and applications.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
DOCX
The AUB Centre for AI in Media Proposal.docx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Encapsulation theory and applications.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Digital-Transformation-Roadmap-for-Companies.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf
Empathic Computing: Creating Shared Understanding
Programs and apps: productivity, graphics, security and other tools
Network Security Unit 5.pdf for BCA BBA.
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
20250228 LYD VKU AI Blended-Learning.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
The AUB Centre for AI in Media Proposal.docx

Under the Hood: Using Spring in Grails