我有一个用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,因为现在从Java8开始就推荐使用Date。
@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通过一些代理和所有的东西做了一些魔法。但一定有一种简单的方法来实现这一点,对吧?
发布于 2020-12-03 02:58:02
来自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,这是一个最终类,Spring (Batch)无法创建代理,因此出现了错误。
我没有看到拥有一个步骤作用域的LocalDate bean的附加值。步骤作用域bean对于后期绑定来自步骤/作业执行上下文的作业参数或属性很有用。但是,如果您真的希望该bean是步骤作用域,您可以尝试另一种代理模式,例如:
@Scope(value = "step", proxyMode = ScopedProxyMode.DEFAULT)https://stackoverflow.com/questions/65108759
复制相似问题