我尝试将数字值从 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/