我已经看到了很多关于我试图用BeanDefinitionRegistryPostProcessor
做什么的变通方法,但我想知道是否有一种方法可以直接使用Spring的bean创建API来覆盖某些行为.
我想看到的是这样的东西(注意@Components
中的"s"):
@Components(prefix="myBean-", numberOfInstances="${myapp.mybean.numberOfInstances}")
public class MyBean {
private final MyService myService;
public MyBean(final MyService myService) {
this.myService = myService;
}
@Scheduled(fixedDelayString = "${myapp.mybean.fixedDelay}")
public myJob() {
System.out.println("I'm working!");
}
}
我基本上是在寻找与@Component
相同的功能,在这里我可以指定创建多少个实例,并生成名称.
正如我之前提到的,我发现做这类事情的唯一方法(特别是现在的计划任务)是使用BeanDefinitionRegistryPostProcessor
来创建实例,或者创建一个自定义SchedulingConfigurer
来手动配置任务,而不使用Spring beans,这意味着Runnable
的所有依赖项都必须连接到SchedulingConfigurer
中,这让人感觉脏兮兮的.
这是否可能——添加一个新注释来扫描并调用其他方法来创建bean?
使现代化
感谢@vince帮助我意识到我不需要每一份工作都有一粒分离豆;我只需要在FixedDelayTask
中多次配置singleton.
@Component
public class MyBean {
private final MyService myService;
public MyBean(final MyService myService) {
this.myService = myService;
}
// Remove @Scheduled here since we have to configure multiple
// instances manually. This is where it would be nice to specify
// how many jobs of the same type you want.
// @Scheduled(fixedDelayString = "${myapp.mybean.fixedDelay}")
public myJob() {
System.out.println("I'm working!");
}
}
@Configuration
@EnableScheduling
public class MyBeanTaskConfiguration implements SchedulingConfigurer {
private final MyBean myBean;
public MyBeanTaskConfiguration(MyBean myBean) {
this.myBean = myBean;
}
@Override
public void configureTasks(final ScheduledTaskRegistrar taskRegistrar) {
for (int i = 0; i < numberOfWorkers; i++) {
taskRegistrar.scheduleFixedDelayTask(
new FixedDelayTask(
myBean,
repeatIntervalMs,
repeatIntervalMs / numberOfWorkers * i + startDelayMs
)
);
}
}
}