Karan Shah
Karan Shah

Reputation: 111

How to run autowired thread in spring boot

I am struggling to run a thread in background with autowired bean in spring boot. From all the internet source I found that if I create a new instance of the object it will throw null because it is not part of spring life cycle and I would instead need to use executorTask and inject it as bean. Here is what I have tried so far with no luck.

My Application.java file


@SpringBootApplication
@EnableAsync
public class Application {

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        SpringApplication.run(Application.class, args);
    }
}

My ThreadConfig.java file [where I actually create the bean for task executor]

@Configuration
public class ThreadConfig {
    @Bean
    public TaskExecutor threadPoolTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix("default_task_executor_thread");
        executor.initialize();

        return executor;
    }
}

The AsyncService.java file

@Service
public class AsynchronousService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private TaskExecutor taskExecutor;

    public void executeAsynchronously() {

        NotificationThread myThread = applicationContext.getBean(NotificationThread.class);
        taskExecutor.execute(myThread);
    }
}

The actual thread that I want to run in background

@Component
@Scope("prototype")
public class NotificationThread implements Runnable {

    @Autowired
    private UserDao userDao;

    public void run() {
        while (true) {
            System.out.println("thread is running...");
            List<User> users = userDao.findAllByType("1"); //Used to get Error here when running directly from main
            try {

                Thread.sleep(1000 );
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

Before when I directly create this thread in main I would get error as mentioned in the comment line. So i switched to taskexecutor. NotificationThread is the thread i want to run in background. But its not working, not sure what changes to make. Would help guidance.

Upvotes: 2

Views: 7171

Answers (1)

R.G
R.G

Reputation: 7121

Need to call the service method executeAsynchronously() to start the flow.

You may auto-wire AsynchronousService to the ThreadAppRunner as follows and call service.executeAsynchronously().

@Component
public class ThreadAppRunner implements ApplicationRunner {

    @Autowired
    AsynchronousService service;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        service.executeAsynchronously()
    }

}

Upvotes: 1

Related Questions