[英]Using LocalDate in Spring context and avoid CGLib issue
我有一份用 Spring Boot Batch 2.2.2 編寫的小作業。 它需要一個日期作為參數,並且由於幾個組件需要該日期,我將它作為一個 bean 放在 Spring 上下文中:
@Bean
@StepScope
public Date processingDate(){
if(isEmpty(applicationArguments.getSourceArgs())){
throw new IllegalArgumentException("No parameter received - expecting a date to be passed as a command line parameter.");
}
SimpleDateFormat sdf = new SimpleDateFormat(EXPECTED_DATE_FORMAT);
String expectedDateFromCommandLine=applicationArguments.getSourceArgs()[0];
try {
return sdf.parse(expectedDateFromCommandLine);
} catch (ParseException e) {
throw new IllegalArgumentException("Expecting the parameter date to have this format : "+ EXPECTED_DATE_FORMAT,e);
}
}
它運作良好,沒有問題。
現在我正在做一些重構,並認為我應該使用 LocalDate 而不是 Date,因為從 Java 8 開始現在建議使用它。
@Bean
@StepScope
public LocalDate processingDate(){
if(isEmpty(applicationArguments.getSourceArgs())){
throw new IllegalArgumentException("No parameter received - expecting a date to be passed as a command line parameter.");
}
String expectedDateFromCommandLine=applicationArguments.getSourceArgs()[0];
return LocalDate.parse(expectedDateFromCommandLine, DateTimeFormatter.ofPattern(EXPECTED_DATE_FORMAT));
}
但是,Spring 不喜歡它:
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class java.time.LocalDate: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class java.time.LocalDate
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:208)
我知道在幕后,Spring 做了一些代理和所有的魔法。但必須有一個簡單的方法來使這成為可能,對吧?
來自StepScope的 Javadoc:
Marking a @Bean as @StepScope is equivalent to marking it as @Scope(value="step", proxyMode=TARGET_CLASS)
現在代理模式TARGET_CLASS
意味着代理將是 CGLIB 代理(參見ScopedProxyMode#TARGET_CLASS ),這意味着將為代理創建 bean 類型的子類。 由於您要聲明一個LocalDate
類型的步驟范圍 bean,它是最終的 class,Spring(批處理)無法創建代理,因此出現錯誤。
我沒有看到具有步驟范圍的LocalDate
bean 的附加值。 步驟范圍 bean 對於后期綁定來自步驟/作業執行上下文的作業參數或屬性很有用。 但是,如果您真的希望該 bean 具有步進范圍,您可以嘗試另一種代理模式,例如:
@Scope(value = "step", proxyMode = ScopedProxyMode.DEFAULT)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.