我有一个 Grails 插件(4.0.1),我试图以与 Grails 无关的方式绑定(bind)属性。
我在 runtime.groovy 中的数据源如下;
dataSource {
dbCreate = 'none'
pooled = true
username = "root"
password = ""
dialect = UTF8MySQL5InnoDBDialect.name
driverClassName = "com.mysql.jdbc.Driver"
properties {
jmxEnabled = false
initialSize = 5
}
remoteDataSources {
disabled = false
urlGenerator = { String host ->
"jdbc:mysql://${host}:3306/myDb?characterEncoding=utf8"
}
}
}
使用 Grails 方法访问上面的配置可以正常工作;
def dbConfig = grailsApplication.config.dataSource
String dbUrl = dbConfig.urlGenerator(thisHost)
但是当我尝试使用与 Grails 无关的方法(Spring Boot)时,我无法绑定(bind)它;
@Value('${dataSource}')
private Map dataSource
单独访问似乎有效;
@Value('${dataSource.remoteDataSources.disabled}')
private boolean disabled
但主要问题是关闭;
@Value('${dataSource.remoteDataSources.urlGenerator}')
private Closure urlGenerator
结果是;
java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'groovy.lang.Closure': no matching editors or conversion strategy found
我不确定我正在尝试做的事情是否可能,但以防万一有人对更好的方法或解决方法有任何想法,那就太好了!
最佳答案
我无法让它工作,所以我使用 @ConfigurationProperties
解决了这个问题而是注释。
我将以下指南应用于我的类似案例;
https://guides.grails.org/grails-configuration-properties/guide/index.html
但注意到以下可能对其他人有所帮助的观察结果;
datasource
必须使用小写值。否则你会得到一个错误。虽然这仍然会与 dataSource
绑定(bind)。在您的属性中进行配置。 例如,例如;
dataSource {
username = 'root'
password = ''
// etc
properties {
jmxEnabled = false
initialSize = 5
}
disabled = false
urlGenerator = { String host ->
"jdbc:mysql://${host}:3306/myDb?characterEncoding=utf8"
}
}
我的课:
@Configuration
@ConfigurationProperties(prefix = "datasource")
class DataSourceConfiguration {
String username
String password
Map<String, String> properties
boolean disabled
Closure urlGenerator
}
这是我在撰写本文时使用 Grails 4.0.1 的经验。我不会将此标记为答案(因为它不会直接回答问题),但我想贡献它,以防它帮助与我处于相同情况且解决方法令人满意的其他人。
关于spring - 使用 @Value 将属性绑定(bind)到 Grails 中的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60760932/