【问题标题】:How to add value to field from file by using annotation?如何使用注释从文件中为字段添加值?
【发布时间】:2021-06-15 02:00:07
【问题描述】:

我正在使用 maven 项目,我需要将信息保存在项目中的文件中,它可以是 .properties/.config 文件,我不在乎,但我需要在这个文件中有初始化字段,例如:

test.properties or test.config
test.name = Test

接下来我想在我的一种方法中使用这个值来初始化字段:

 public String sendName()  {
        @Value("${test.name}")
        String name;
        return name;
      }

但是 lombok 注释不起作用,我使用的是 maven 项目,它不是 Spring 项目,我知道其中一个选项是扫描此文件并获取我想要的值,但我希望这是另一个更简单的选项:)

【问题讨论】:

标签: java maven properties configuration


【解决方案1】:

我手动创建 META-INF 目录并添加 application.properties,当我点击注释中的“user.test”时,我被重定向到我的属性文件

【讨论】:

    【解决方案2】:

    使用这两个注解:

    @Inject // javax.inject.Inject
    @ConfigProperty(name = "name of the property", defaultValue = "if the property can't be found") // org.eclipse.microprofile.config.inject.ConfigProperty
    Field declaration;
    

    必须在 resources/META-INF/microprofile-config.properties 文件中定义属性。 例如:

    Java 代码:

    @Inject
    @ConfigProperty(name = "mysql.server.host", defaultValue = "localhost")
    String remoteIP;
    

    resources/META-INF/microprofile-config.properties 文件:

    mysql.server.host=192.168.100.25
    mysql.server.port=1111
    

    【讨论】:

    • 我是空的,和你描述的完全一样,但之后我的字段是空的
    • 属性文件应该在你的类路径中。是可用的么?此注解首先查找系统属性,然后查找 JVM 属性,然后查找类路径上的属性文件。
    • 我在下面添加了帖子
    • 我不知道出了什么问题
    • 当我添加 defaultValue 时,我仍然为空
    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多