[英]How to pass a number parameter from a properties file to a Spring annotation number (long, or int, or Integer, etc) parameter
我嘗試將 Spring 屬性文件中的數字值傳遞給 Annotation long 屬性,我想知道如何正確設置非字符串參數。 我嘗試使用以下方式,顯然,由於Incompatible types. Found: 'java.lang.String', required: 'long'
Incompatible types. Found: 'java.lang.String', required: 'long'
我的問題是“如何將屬性文件中的數字參數傳遞給 Spring 注釋數字參數”
應用程序屬性
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}"
)是一個字符串,而不是一個長字符串(正如注釋的定義所預期的那樣類MyAnnotation
)。
一種解決方案是將 myParameter 的類型更改為String
,然后使用 Spring 的自動裝配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 ...
}
這里有幾個可能有效的選項:
@MyAnnotation(myParameter = "#{ T(java.lang.Long).parseLong('${email.config.port}')}")
my.parameter=10L
。 如果您在此之后得到NumberFormatException
- 這意味着 Spring 無法找到該屬性。
參考資料和有用的資料:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.