创建一个springbootUtil类获取springboot上下文,获取springboot上下文中的bean,在bean上执行具体的业务逻辑。

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

    //获取应用上下文。
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //按名称获取一个 bean。
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //按类获取一个bean。
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //按名称和 Clazz 返回指定的 bean。
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

}

创建一个可以处理任何业务逻辑的简单线程类。

ProjectRealTask.java

package springBootPlugin;

import org.springframework.stereotype.Component;

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

创建一个主调用类,在调用类中获取springbootUtil中的bean,执行bean内部的业务逻辑,实现对业务逻辑的插件化管理。

ProjectThread.java

package springBootPlugin;

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

@Component
public class ProjectThread {

    //这里需要调用一些bean,第三方业务逻辑或者插件。
    public void runThreadTaskLogic(){

        //创建一个线程池。
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(100);
        taskExecutor.setThreadNamePrefix("TestExecute_");
        taskExecutor.initialize();

        //按类名获取 bean。
        ProjectRealTask realTask = SpringBootUtil.getBean(ProjectRealTask.class);

        //具体的 bean 操作。
        taskExecutor.submit(realTask);
    }

}

这种方式非常适合多任务、多线程的业务逻辑场景,让bean的管理更加灵活方便。

发表回复

Thanks for your support to bet365fans!