如何在 spring 中通过执行程序服务创建的线程中注入服务

how to inject a service in a thread created through executor service in spring

我创建了一个简单的服务,例如...,稍后我必须从数据库中获取一些数据

package com.spring.scheduler.example.springscheduler;

import org.springframework.stereotype.Service;

@Service
public class ExampleService {

    private String serviceName;
    private String repository;

    public String getServiceName() {
        return serviceName;
    }
    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }
    public String getRepository() {
        return repository;
    }
    public void setRepository(String repository) {
        this.repository = repository;
    }
}

这是我为 运行 个不同线程创建的任务调度程序。

@Component
public class TaskSchedulerService {

    @Autowired 
    ThreadPoolTaskScheduler threadPoolTaskScheduler;
     public ScheduledFuture<?> job1;        
     public ScheduledFuture<?> job2;

     @Autowired 
    ApplicationContext applicationContext;


     @PostConstruct
     public void job1() {
         //NewDataCollectionThread thread1 = new NewDataCollectionThread();
         NewDataCollectionThread thread1 = applicationContext.getBean(NewDataCollectionThread.class);
         AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
         factory.autowireBean(thread1);
         factory.initializeBean(thread1, null);
         job1 = threadPoolTaskScheduler.scheduleAtFixedRate(thread1, 1000);
     }

 }

这是一个试图从调度程序调用的线程。我尝试使用应用程序上下文强制创建服务实例,但它没有创建。

@Configurable
@Scope("prototype")
public class NewDataCollectionThread implements Runnable {

private static final Logger LOGGER = 
LoggerFactory.getLogger(NewDataCollectionThread.class);

@Autowired
private ExampleService exampleService;

@Override
public void run() {
    LOGGER.info("Called from thread : NewDataCollectionThread");
    System.out.println(Thread.currentThread().getName() + " The Task1 
    executed at " + new Date());
    try {
        exampleService.setRepository("sdasdasd");
        System.out.println("Service Name :: " + 
        exampleService.getServiceName());
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

}

请建议有哪些可能的实现方式。

尝试这样的事情:

@Autowired 
private AutowireCapableBeanFactory beanFactory;

@PostConstruct
public void job1() {
    NewDataCollectionThread thread1 = new NewDataCollectionThread();
    beanFactory.autowireBean(thread1);
    job1 = threadPoolTaskScheduler.scheduleAtFixedRate(thread1, 1000);
}

我在 NewDataCollectionThread 中成功注入了 Example 服务。