register
other register

Thursday, November 03, 2011

Initialising in Grails Service

Attributes can be initialised from config in grails service by implementing the Spring InitializingBean interface. In the afterPropertiesSet method, set the attributes.

class SomeService implements InitializingBean {
def grailsApplication
private static String TOKEN

void afterPropertiesSet() {
TOKEN = grailsApplication.config.token
println this
}

def someMethod() {
println TOKEN
println this
}
}

In unit and integration test, the afterPropertiesSet method has to be called otherwise the TOKEN won't be set. But noticeably, in unit test, the instances printed out by 'println this' are different, although grails service by default is a singleton implementation; but in integration test, the instance from 'println this' is the same.

In unit test:

@Before
void setUp() {
service.afterPropertiesSet()
}
}

In integration test:

private static service

@BeforeClass
static void fixtureSetUp() {
service.afterPropertiesSet()
}

No comments: