使用 Spring @Value 时如何进行简单的属性验证 [英] How to make simple property validation when using Spring @Value

查看:39
本文介绍了使用 Spring @Value 时如何进行简单的属性验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查 ${service.property} 是否不是空字符串,如果是,则抛出某种可读异常?它必须在 Bean 创建期间发生.

How can I check, if ${service.property} is not an empty string and if so, throw some kind of readable exception? It must happen during Bean creation.

@Component
public class Service {

  @Value("${service.property}")
  private String property;
}

我正在寻找最简单的方式(最少编写的代码).如果使用注释会很棒.

I am looking for the easiest way (least written code). Would be great if by using annotations.

我目前的解决方案是在 setter 中为属性执行手写"验证,但是对于这么简单的事情来说代码有点太多了.

My current solution is to perform "handwritten" validation inside setter for the property, but is a little too much code for such easy thing.

提示:我寻找了某种使用 SpEL 的方法,因为我已经在 @Value 中使用了它,但据我所知,它不会那么容易/干净.但可能忽略了一些东西.

Hint: I looked for some way to use the SpEL, since I use it already inside @Value, but as far I have found out, it would not be that easy/clean. But could have overlooked something.

澄清:预期的行为是,应用程序不会启动.目标是确保设置所有属性,尤其是字符串属性不为空.错误应该说清楚,缺少什么.我不想设置任何默认值!用户必须全部设置.

Clarification: Expected behaviour is, that the application will not start up. The goal is to assure, that all properties are set, and especially, that string properties are not empty. Error should say clearily, what is missing. I don't want to set any defaults! User must set it all.

推荐答案

您可以将组件本身用作属性占位符.然后你可以使用任何你想要的验证.

You can use the component as a property placeholder itself. And then you may use any validation that you want.

@Component
@Validated
@PropertySource("classpath:my.properties")
@ConfigurationProperties(prefix = "my")
public class MyService {

    @NotBlank
    private String username;

    public void setUsername(String username) {
        this.username = username;
    }

    ...
}

您的 my.properties 文件将如下所示:

And your my.properties file will look like this:

my.username=felipe

这篇关于使用 Spring @Value 时如何进行简单的属性验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆