Posted By

laurenceosx on 03/29/13


Tagged

groovy


Versions (?)

Groovy Spring Refreshable Script Bean - findScriptResourcePath


 / Published in: Groovy
 

URL: http://my.safaribooksonline.com/book/programming/java/9781430224990/scripting-in-spring/refreshing_beans_from_scripts

Created this to generate file:/ script path for Groovy Refreshable Spring Beans for use in applicationContext.groovy because refresh feature wouldn't work when Groovy script is looked up on classpath.

  1. // applicationContext.groovy
  2.  
  3. import org.springframework.scripting.groovy.GroovyScriptFactory
  4. import org.springframework.scripting.support.ScriptFactoryPostProcessor
  5. import org.codehaus.groovy.grails.commons.spring.DefaultBeanConfiguration
  6.  
  7. ////////////////////////////////////////////////////////////
  8. String findScriptResourcePath( String aScriptResourcePath) {
  9. // Created this to generate script path for Groovy Refreshable Spring Beans
  10. // for use in applicationContext.groovy because refresh feature wouldn't work
  11. // when Groovy script is looked up on classpath.
  12. // e.g. sample arg 'src/main/resources/USA.groovy' when running gradle runJetty task in IDEA.
  13. File f1 = new File( aScriptResourcePath ).canonicalFile;
  14. if (f1.exists()) {
  15. return f1.toURI().toString(); // most likely running in IDE
  16. }
  17. // try again
  18. // special case
  19. String token1 = 'src/main/resources';
  20. if ( aScriptResourcePath.startsWith( token1 ) ) {
  21. return findScriptResourcePath( aScriptResourcePath - token1 );
  22. } else {
  23. // note: refresh feature will probably not work in this case
  24. def result = this.getClass().getResource( aScriptResourcePath );
  25. return (result != null) ? result.toString() : null; // e.g. returns file:/C:/blah/blah/blah.groovy
  26. }
  27. }
  28. ////////////////////////////////////////////////////////////
  29.  
  30. beans {
  31. importBeans('classpath:applicationContext.xml')
  32.  
  33. String USAscriptUriPath = findScriptResourcePath('src/main/resources/USA.groovy')
  34.  
  35. // setup refreshable usa bean
  36. usa(GroovyScriptFactory, USAscriptUriPath) { DefaultBeanConfiguration bean ->
  37. capital = 'Washington, D.C.'
  38. population = 617996
  39.  
  40. bean.beanDefinition.setAttribute( ScriptFactoryPostProcessor.REFRESH_CHECK_DELAY_ATTRIBUTE, 5000 )
  41. }
  42.  
  43. scriptFactoryPostProcessor(ScriptFactoryPostProcessor) {
  44. defaultRefreshCheckDelay = 5000
  45. }
  46. }

Report this snippet  

You need to login to post a comment.