spring调度任务和一个懒bean

gfttwv5a  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(437)

有没有人知道如何创建一个调度任务,它不使用application start初始化lazybean,但只在必须执行该任务时才这样做?
例如:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"
       default-lazy-init="true">

    <!-- Configure the scheduler -->
    <task:scheduler id="myScheduler" pool-size="10"/>

    <!-- Configure parameters -->
    <task:scheduled-tasks scheduler="myScheduler">
        <task:scheduled ref="secondBean" method="run" fixed-delay="5000" initial-delay="5000"/>
    </task:scheduled-tasks>

    <bean name="firstBean" class="com.mkazm.lazy.User"/>
    <bean name="secondBean" class="com.mkazm.lazy.User"/>
</beans>

简单测试类:

@Slf4j
public class User implements Runnable, BeanNameAware {
    private String beanName;

    @Override
    public void run() {
        log.warn("I am running {}", beanName);
    }

    @PostConstruct
    private void post() {
        log.warn("Initialized {}", beanName);
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }
}

输出:

2021-02-25 21:33:49.527  INFO DESKTOP-M766312 --- [           main] c.m.l.PostProcessorApplication           : No active profile set, falling back to default profiles: default
2021-02-25 21:33:50.251  WARN DESKTOP-M766312 --- [           main] c.m.l.User                               : Initialized secondBean
2021-02-25 21:33:50.287  INFO DESKTOP-M766312 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'myScheduler'
2021-02-25 21:33:50.399  INFO DESKTOP-M766312 --- [           main] c.m.l.PostProcessorApplication           : Started PostProcessorApplication in 1.48 seconds (JVM running for 3.352)
2021-02-25 21:33:55.397  WARN DESKTOP-M766312 --- [  myScheduler-1] c.m.l.User                               : I am running secondBean
2021-02-25 21:34:00.411  WARN DESKTOP-M766312 --- [  myScheduler-1] c.m.l.User                               : I am running secondBean

我找到的唯一可能的解决方案是创建一个代理对象,其中包含对实际bean的lazy@autowired引用。

bmp9r5qi

bmp9r5qi1#

使用java config,将bean声明为lazy:

@Bean
@Lazy
User user1() {
  return new User();
}

并将注入点标记为惰性:

@Component
public class CustomJob {

  private final User user;

  public CustomJob(@Lazy @Qualifier("user1") User user) {
    this.user = user;
  }

  @Scheduled(initialDelay = 5000L, fixedRate = 3 * 1000L)
  void execute() {
    user.run();
  }
}

相关问题