Groovy Spring Bean for Static Factory
Join the DZone community and get the full member experience.
Join For Free I started playing around with Grails again recently and ran into a problem trying to create a bean in the Grails resources.groovy
file for a static factory. After several frustrating hours trying to
find the right combination, I eventually stumbled upon an answer.
The factory I was trying to create a bean from was the JAX-RS Client API class ClientBuilder.newClient() which returns a Client object.
Here is what the bean definition looks like in my Grails resources.groovy file:
import javax.ws.rs.client.ClientBuilder beans = { httpClient(ClientBuilder) { bean -> bean.factoryMethod = 'newClient' bean.destroyMethod = 'close' } }
Then in your Grails service or controller you can autowire or inject the bean by doing the following:
class FooService { def httpClient def get(url) { return httpClient.target(url).request().get() } }
Hope it helps the next person.
Published at DZone with permission of James Lorenzen, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments