我搜索了互联网的大半部分,但没有找到明确的答案...
我想做一件简单的事情:像在Grails中一样,在控制器中使用MessageSource
类型的单例来显示i18n消息。
我想从以下文件初始化我的messageSource
:src/main/resources/my/package/i18n/Messages*.properties
test=FooBar
初始化尝试:
class AppConfig {
@Singleton
MessageSource messageSource() {
new ResourceBundleMessageSource( 'my.package.i18n.Messages' )
}
}
控制器要注入:
class CRUDController<T> {
@Inject
MessageSource messageSource
@Transactional( readOnly=true )
@Get( '/' )
Map<String,Object> list() {
log.info "$messageSource -> ${messageSource.getMessage( 'test', MessageSource.MessageContext.DEFAULT )}"
[:]
}
}
日志信息将显示以下内容:
io.micronaut.runtime.context.CompositeMessageSource@79a1d030->可选。空
因此,messageSource会因某种原因(和某处)被错误初始化。
做那个简单的事情最简单直接的方法是什么?
最佳答案
请参见https://github.com/jeffbrown/injecteermessagesource上的项目。
https://github.com/jeffbrown/injecteermessagesource/blob/beba0773d41cb475d8d837acc19d0dd41f5b4431/src/main/groovy/injecteermessagesource/CRUDController.groovy
package injecteermessagesource
import io.micronaut.context.MessageSource
import javax.inject.Inject
class CRUDController<T> {
protected final Class<T> clazz
@Inject
MessageSource messageSource
protected CRUDController( Class<T> clazz ) {
this.clazz = clazz
}
}
https://github.com/jeffbrown/injecteermessagesource/blob/471f6436511c99511426094a8c269112e93149e6/src/main/groovy/injecteermessagesource/PersonController.groovy
package injecteermessagesource
import io.micronaut.context.MessageSource
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller('/people')
class PersonController extends CRUDController<Person> {
protected PersonController() {
super(Person)
}
@Get('/')
String index() {
def context = MessageSource.MessageContext.DEFAULT
def message = messageSource.getMessage('test', context)
message.get()
}
}
https://github.com/jeffbrown/injecteermessagesource/blob/471f6436511c99511426094a8c269112e93149e6/src/main/groovy/injecteermessagesource/AppConfig.groovy
package injecteermessagesource
import io.micronaut.context.MessageSource
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.context.i18n.ResourceBundleMessageSource
@Factory
class AppConfig {
@Bean
MessageSource messageSource() {
new ResourceBundleMessageSource('my.somepackage.i18n.Messages')
}
}
https://github.com/jeffbrown/injecteermessagesource/blob/471f6436511c99511426094a8c269112e93149e6/src/main/resources/my/somepackage/i18n/Messages.properties
test=FooBar
看来一切正常:
$ curl localhost:8080/people
FooBar
关于java - 如何初始化一个MessageSource注入(inject) Controller ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57553500/