Java Reference
In-Depth Information
import
org.springframework.beans.factory.annotation.Autowired
import
org.springframework.context.annotation.Bean
import
org.springframework.context.annotation.Configuration
import
org.springframework.context.annotation.Scope
@Configuration
class
GroovyConfig {
@Autowired
AccountDAO dao
@Bean @Scope("prototype")
Account prototypeAccount() {
int
newId = dao.createAccount(100.0)
new
Account(id:newId,balance:100.0)
}
}
The
@Configuration
and
@Bean
annotations are the same as their counterparts in the
Javaconfigurationfile.The
AccountDAO
isautowiredinasbefore.Thistime,though,the
@Scope
annotation is used to indicate that the
prototypeAccount
is not a singleton.
The implementation uses the DAO to create each new account with the given balance and
then populates an
Account
object with the generated ID.
To prove this is working properly, here is another Spock test in the next listing.
Listing 7.25. A Spock test for the prototype
Accounts
package
mjg.spring.services
import
mjg.spring.entities.Account
import
org.springframework.beans.factory.annotation.Autowired
import
org.springframework.context.ApplicationContext
import
org.springframework.test.context.ContextConfiguration
import
org.springframework.transaction.annotation.Transactional
import
spock.lang.Specification
@ContextConfiguration("classpath:applicationContext.xml")
@Transactional
class
AccountSpec
extends
Specification {
@Autowired
ApplicationContext ctx
def
"prototype accounts have consecutive ids and balance 100"() {
when:
Account a1 = (Account) ctx.getBean("prototypeAccount")