Ces*_*sar 3 java dns grails groovy controller
我有以下Grails域类:
class Product {
String name
Float basePrice
Category category
String image = "default.jpg"
static constraints = {
name(size:3..25, blank:false)
basePrice(scale:2, nullable:false)
category(inList:Category.list(), nullable:false)
image(blank:false)
}
}
Run Code Online (Sandbox Code Playgroud)
从控制器,我想获得图像属性的默认值(在本例中为"default.jpg").像这样的东西:
def productInstance = new Product(params)
productInstance.image = getProductPicturePath() ?: Product().image
Run Code Online (Sandbox Code Playgroud)
getProductPicturePath返回一个图像路径,但是如果没有提交图像,控制器应该用默认值替换null值.虽然我当然可以这样写:
productInstance.image = getProductPicturePath() ?: "default.jpg"
Run Code Online (Sandbox Code Playgroud)
它肯定不是很干,我宁愿将默认值保存在一个地方.我怎样才能做到这一点?
显而易见的解决方案是将其声明为常量然后引用它.
class Product {
static DEFAULT_IMAGE = "default.jpg"
String name
Float basePrice
Category category
String image = DEFAULT_IMAGE
static constraints = {
name(size:3..25, blank:false)
basePrice(scale:2, nullable:false)
category(inList:Category.list(), nullable:false)
image(blank:false)
}
}
productInstance.image = getProductPicturePath() ?: Product.DEFAULT_IMAGE
Run Code Online (Sandbox Code Playgroud)
更好的是,getProductPicturePath()返回默认值.