Search code examples
grailsgsp

grails groovyPageRenderer injecting in file inside src/groovy


I want to inject groovyPageRenderer in a src/groovy/GSPFormatter, How can I do that without calling the new constructor?

EDIT

package gsprenderer
import spud.core.FormatterInterface
import grails.gsp.PageRenderer

class GSPFormatter implements FormatterInterface {

   PageRenderer groovyPageRenderer = grailsApplication.mainContext.getBean('groovyPageRenderer')

   String compile(String content) {
      groovyPageRenderer.render(view: new ByteArrayOutputStream().write(content.bytes), null)
   }
}

is my code in src/groovy/GSPFormatter (basically with the default injection mechanism which doesn't work either)


Solution

  • I think, you are referring to grails.gsp.PageRenderer ... btw, I am using Grails 3.3.0

    Here is a small (tested) example -

    In application.yml

    grails:
        spring:
            bean:
                packages:
                        - ovr
    

    in scr/groovy/ovr

    package ovr.renderer
    
    import grails.gsp.PageRenderer
    import org.springframework.beans.factory.annotation.Autowired
    import org.springframework.stereotype.Component
    
    @Component
    class CustomRenderer {
        @Autowired
        PageRenderer pageRenderer
    
        def page(){
            pageRenderer.render(view: '/myrenderer', model: [hello: 'hello'])
        }
    
    }
    

    in controller

    @Autowired
    CustomRenderer customRenderer
    
    def myPage(){
        render customRenderer.page()
    }
    

    in views/myrenderer.gsp

    ${hello}
    

    Related post -

    Accessing Grails services from src/groovy

    How to inject Grails services into src/groovy classes

    PS - if you describe your bean in /conf/spring/resources.groovy please escape the part in application.yml (given above)