java - 如果无法解析属性,带有@Value Annotation 的 Grails 3 不会返回 null

标签 java grails spring-boot

Grails 3.2.8 应用程序使用 src/main/resources 文件夹中的 application.properties 文件,如果底层 spring 能够解析属性,它就可以完美工作。

2017-04-18 15:01:09.957 DEBUG --- [nio-8080-exec-1] o.s.c.e.PropertySourcesPropertyResolver  : Found key 'com.win.test' in [applicationConfig: [classpath:/application.yml]] with type [String]

2017-04-18 15:01:09.957 DEBUG --- [nio-8080-exec-1] o.s.c.e.PropertySourcesPropertyResolver  : Found key 'com.win.test' in [environmentProperties] with type [String]

但是,如果 application.properties 或 application.yml 文件中不存在属性,它不应该返回“null”吗?
2017-04-18 15:01:09.956 DEBUG --- [nio-8080-exec-1] o.s.c.e.PropertySourcesPropertyResolver  : Could not find key 'widget.name' in any property source

服务代码片段。
class TestService {

    @Value('${widget.name}')
    def name
    @Value('${com.win.test}')
    def test

    def serviceMethod() {
        println name
        println test
    }
}

输出:
${widget.name}
hello

所以 name 应该被解析为 null 因为 widget.name 在属性文件中不存在,但在这种情况下它的值是 value Annotation 的表达式。

最佳答案

如果键不存在,您可以指定所需的值:
@Value('${widget.name:#{NULL}}') def name

关于java - 如果无法解析属性,带有@Value Annotation 的 Grails 3 不会返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43480554/

相关文章:

spring-boot - 使用docker时,如何在Eureka Client中保持Eureka服务器URL动态?

java - MySQL密码包含 '=' Spring Boot密码错误问题

java - 如何解决将 Java 8 代码迁移到 Java 11 的依赖和包问题

hibernate - 从 Hibernate 3/Grails 2.2.4 迁移到 Hiberate 5/Grails 3.2.4 时出现 MappingException

postgresql - 使用Grails db-migration插件更改列的数据类型

Grails:连接是只读的。不允许进行导致数据修改的查询

java - 使用 Spring Autowired 注解时的 Nullpoint

java - 如何用Gson反序列化未知维度的数组?

java - spring servlet 映射到 .html 会响应工作,但映射到非 html 结尾 url 不会

java - 组位置始终返回 0