Create a springbootUtil class to obtain the springboot context, obtain the beans in the springboot context, and execute specific business logic on the beans.

SpringBootUtil.java

package springBootPlugin;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringBootUtil implements ApplicationContextAware{
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringBootUtil.applicationContext == null) {
            SpringBootUtil.applicationContext = applicationContext;
        }
    }

    //Get the application context.
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //Get a bean by name.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //Get a bean by class.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //Returns the specified bean by name and Clazz.
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

}

Create a simple thread class that can handle any business logic.

ProjectRealTask.java

package springBootPlugin;

import org.springframework.stereotype.Component;

@Component
public class ProjectRealTask implements Runnable {
    @Override
    public void run() {
            System.out.println("test ProjectRealTask");
    }
}

Create a main calling class, obtain the bean in springbootUtil in the calling class, execute the business logic inside the bean, and realize the plug-in management of the business logic.

ProjectThread.java

package springBootPlugin;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

@Component
public class ProjectThread {

    //Here you need to call some beans, third-party business logic or plug-ins.
    public void runThreadTaskLogic(){

        //Create a thread pool.
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(100);
        taskExecutor.setThreadNamePrefix("TestExecute_");
        taskExecutor.initialize();

        //Get a bean by class name.
        ProjectRealTask realTask = SpringBootUtil.getBean(ProjectRealTask.class);

        //Concrete bean operations.
        taskExecutor.submit(realTask);
    }

}

This method is very suitable for multi-task and multi-thread business logic scenarios, making bean management more flexible and convenient.

发表回复

Thanks for your support to bet365fans!