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

问题描述 投票:0回答:1

我已经创建了一个像...这样的简单服务,我必须在以后从数据库中获取一些数据

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();
    }
    }

}

请建议实现它的可能方法是什么。

java spring spring-boot executorservice
1个回答
0
投票

尝试这样的事情:

@Autowired 
private AutowireCapableBeanFactory beanFactory;

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

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

© www.soinside.com 2019 - 2024. All rights reserved.