context.GrailsContextLoaderListener初始化时出错 application:使用类[Domain Class(auth.Role)]上的方法 在Grails应用程序之外。如果在测试环境中运行 正确使用模拟API或引导Grails。
java.lang.IllegalStateException:类[Domain Class(auth.Role)]在Grails应用程序之外使用。如果跑步 在使用模拟API或bootstrap 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)
}
}
}
}
答案 0 :(得分:1)
如果您使用
static mapWith = 'none'
它不会将此域类映射到任何数据库,因此无法访问(因为它不是持久的)。将映射添加到任何数据库(它甚至可能是默认的h2数据库),它将再次工作。