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

查看:292
本文介绍了使用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.

我当前的解决方案是在属性的设置器中执行手写"验证,但是对于这种简单的事情来说,代码太多了.

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 文件将如下所示:

my.username=felipe

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

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