I have this .groovy file
@RestController
class SimpleBeanApp{
@Autowired
String text
@RequestMapping("/")
String index(){
"You can do: ${text}!"
}
beans {
text String, "-Spring Boot with Groovy beans-"
}
}
When i run it I have
file...beans.groovy: 12: unexpected token: beans @ line 12, column 2. beans
which is the beans{
, I have tried adding an annotation @Bean
before beans
but it doesn't work.
You are trying to inject a String text
with the @Autowired
annotation at the beginning of your controller class.
Spring searches beans with type String
in its dependency injection scopes. The line that doesn't compile was supposed to provide that missing bean.
I'm not familiar with groovy, but it has to look something like this:
@Bean
String text() {
return "-Spring Boot with Groovy beans-"
}
That's how you create a bean of type String
and name text
. It will be found by springs dependency injection framework and linked to the @Autowired
field at the top of your controller.
what mana sugests is 'Java' construct. It will work, but is not groovy-ish. Indeed, groovy SHOULD allow you to create beans in a more 'groovy' way; by providing a beans closure.
I was searching to solve the same issue myself today. Turned out I had to find out by myself... So providing here my 2 cents.
That 'beans' definition is actually a method belonging to a GroovyBeanDefinitionReader
So, you need to create one such class and invoke its 'beans' method providing it a closure will the beans definition, like in the example in the javadoc. (I love groovy, but from time to time I feel like I need to understand what the code means in a C-programmer fashion to understand what I'm really doing... must be bound to ageing...)
Note you need to get hold of the application context. One way I found (there could be better ways) is:
class SimpleBeanApp implements ApplicationContextAware {
...
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
def beanConfig = new GroovyBeanDefinitionReader(applicationContext)
beanConfig.beans {
text String, "-Spring Boot with Groovy beans-"
}
}
}
Or, you could also put your beans configuration in a separate groovy script to be loaded while configuring your spring application. Like:
static void main(String[] args) {
SpringApplication.run ([DemoApplication,new ClassPathResource('/DemoConfig.groovy')] as Object[], args)
}
And put within a DemoConfig.groovy file the beans configuration:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
beans {
...
}
Note that DemoConfig.groovy should be located in: /src/main/resources/DemoConfig.groovy
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.