1
context.GrailsContextLoaderListener錯誤初始化 應用:採用上類的方法[域類(auth.Role)] 外的Grails應用程序。如果在測試 的環境中正確使用模擬API或引導Grails運行。java.lang.IllegalStateException:上類的方法[域類]的Grails應用程序之外使用
java.lang.IllegalStateException:類[Domain Class(auth.Role)]上的方法在Grails應用程序之外使用。如果在正確使用模擬API或引導Grails 的測試環境中運行 。
此異常是在該行拋出:
def existingRole = Role.findByAuthority(role) // Code Interrupts
Role.groovy
import org.bson.types.ObjectId
class Role {
// static mapWith = 'mongo' (For mongoDb we have plugin, so this is working)
static mapWith = 'none' //(Migrating MongoDB to postgreSql so changed mapWith to 'none')
ObjectId id
String authority
static constraints = {
authority blank: false, unique: true
}
}
UserService.groovy
@Transactional
class UserService {
def grailsApplication
/**
* Create Users with supplied roles
* @param usersAndRoles map of user:role
*
* @return
*/
def createUsers(def usersAndRoles) {
// [user:ROLE_USER, manager:ROLE_MANAGER, admin:ROLE_ADMIN]
// For supplied list of user:role, create user with role
usersAndRoles.each { key, value ->
def user = User.findByUsername(key)
if (!user) {
def fields = grailsApplication.config."${key}"
user = new User(username: fields.username,
password: fields.password,
email: fields.email,
passwordExpired: true).save(flush: true)
}
// Get the role for this user, set authorities to this role and save
def role = Role.findByAuthority(value)
user.authorities = [role]
user.save(flush: true)
}
}
/**
* Create supplied roles
* @param roles list of roles
* @return
*/
def createRoles(def roles) {
roles?.each { role ->
def existingRole = Role.findByAuthority(role) // Code Interrupts Here
if (!existingRole) {
new Role(authority: role).save(flush: true)
}
}
}
}