java - 如何将数字参数从属性文件传递到 Spring 注释数字(long、int、Integer 等)参数

标签 java spring annotations

我尝试将数字值从 Spring 属性文件传递到注释长属性,我想知道如何正确设置非字符串参数。我尝试使用以下方式,显然,由于 类型不兼容,我们无法用字符串定义参数。找到:'java.lang.String',必需:'long'

我的问题是“如何将数字参数从属性文件传递到 Spring 注释数字参数”

application.properties

my.parameter=10

MyAnnotation.java

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {

    long myParameter() default 0;
}

MyClass.java

@Component
@MyAnnotation(myParameter = "${my.parameter}") //incompatible types long and String
public class MyClass {

//some code
}

最佳答案

您的尝试将在编译阶段早期失败(因此,不会在 Spring 解析应用程序属性的运行时失败),因为模板 ("${my.parameter}") 是一个字符串,而不是一个long(正如注释类 MyAnnotation 的定义所期望的那样)。

解决方案是将 myParameter 的类型更改为 String,然后使用 Spring 中的 Autowiring ConfigurableEnvironment 解析它(在需要时)。

例如:

@Component
@MyAnnotation(myParameter = "${my.parameter}")
public class FooComponent
{
    @Autowired private ConfigurableEnvironment env;

    @PostConstruct
    private void initialize()
    {
        MyAnnotation a = FooComponent.class.getAnnotation(MyAnnotation.class);
        // resolve using our application properties
        String s = env.resolvePlaceholders(a.myParameter()));
        // convert to long
        long n = Long.valueOf(s);
        // use n somehow ...
    }


    // ... more methods ...
} 

关于java - 如何将数字参数从属性文件传递到 Spring 注释数字(long、int、Integer 等)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72309119/

相关文章:

java - Android spinner Data Binding 使用 XML 并显示选定的值

spring - @ Builder,@ NoArgsConstructos和@AllArgsConstructor?

java - Spring In CorrectResultSizeDataAccessException 查询返回 Long 值? java

java - JAXB编码

ios - 如何在 MKMapView 上显示室内标注

java - 如何给Annotation添加限制?

java - JApplet 无法连接到互联网问题 - 如何使其受信任?

java - JTextArea 和 JTextPane 字体渲染

java - 索引到 800 GB 集群时出现 GC 暂停和 OOM 错误

java - 基于 Spring 注释的 DI 与 xml 配置?