add ThreadPoolTaskExecutor to existing applicaiton context programatically

Viewed 26

I am using existing applicationContext.xml that is being used for our existing web application to create a new console based java process.

This process or accounting server is to process tasks of different companies (lets say 2 different companies at a time). For this ThreadPoolTaskExecutor gives a guarantee that no more than the defined limit threads will be executed.

In below snippet when I try to get the "taskExecutor" from application context it is throwing exception that no such bean exists

is it the correct way to register a component ? as am not getting the thread pool bean from application context, is it properly registered with application context ?

public static void main(String[] args) {
        LOGGER.info("Starting Accounting Server ...");
        
        LOGGER.info("initializing applicationContext ... from " + APPLICATION_CONTEXT_XML_FULL_PATH);

        try (AbstractApplicationContext applicationContext = new FileSystemXmlApplicationContext("file:" + APPLICATION_CONTEXT_XML_FULL_PATH)) {
            LOGGER.info("... applicationContext initialized");

            
            ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
            threadPool.setCorePoolSize(MAX_RUNNING_THREADS);
            threadPool.setMaxPoolSize(MAX_RUNNING_THREADS);
            threadPool.setThreadNamePrefix("T--ACCOUNTING-THREAD--");
            threadPool.initialize();
            
            Object obj = applicationContext.getBeanFactory().initializeBean(threadPool, "taskExecutor");
            // obj is returned
            
            obj = applicationContext.getBean("taskExecutor"); // <--------- throws exception with no such bean
            
            AccountingQueueTransacitonService accountingQueueTransacitonService = applicationContext.getBean(AccountingQueueTransacitonService.class);
            
            /*
            while (hastasks) {
                // TODO:
                // get tasks
                // add to thread and push to thread pool
                // get some sleep
                // update hastasks flag
            }
            */
        } catch (Exception e) {
            LOGGER.error(e, e);
        } finally {
            LOGGER.info("closed application context ...");
        }
        
        LOGGER.info("Ending Accounting Server gracefully ...");
    }
0 Answers
Related