Spring引导不会从groovy bean builder中加载bean

时间:2014-04-24 04:09:21

标签: spring-boot

我一直在尝试创建一个使用Groovy bean构建器的简单springboot程序,但我遗漏了一些东西:

@EnableAutoConfiguration
class MyApplication {

    public static void main(String[] args) {
        logger.info "Starting MyApplication..."

        Object[] sources = [MyApplication.class, new ClassPathResource("bb.groovy")]
        SpringApplication.run(sources, args)
    }
}

//MyController.groovy
@RestController
class MyController {
    ConfigObject configObject
    MyService myService

    @RequestMapping("/home")
    String home() {
        return myService.getSomeData()
    }

}

//src/main/resources/bb.groovy
beans = {
    myService(MyService) {
        url = "http://www.spring.io"
    }

    configObject(ConfigObject) {
        new ConfigSlurper().parse("Config.groovy")
    }

    myController(MyController) {
        configObject = ref('configObject')
        myService = ref('myService')
    }
}

SpringBoot启动很好,但我在/ home获得了404。我也没有在启动时看到任何尝试(sys out)从bb.groovy加载bean

我知道这可以从Where to put Groovy bean definitions in a Spring Boot webapp?的答案中获得,但我必须遗漏一些东西......

1 个答案:

答案 0 :(得分:3)

回答我自己的问题。这不是spring boot的问题,而是使用bean的dsl语法。

必须是bean {}。不是beans = {}

删除等号可以加载配置。我使用的是grails方式的resources.groovy,其语法是beans = {}

另外,为了注入Config.groovy,我不得不使用

新的ConfigSlurper()。解析(Config)而不是 新的ConfigSlurper()。解析(" Config.groovy")

其中Config.groovy是与bb.groovy在同一目录中的文件。

(参考:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#cli-groovy-beans-dsl

相关问题