spring带bean和config,通过main启动测试

main方法:

java 复制代码
package com.xxx.tmp;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
    public static void main(final String[] args) {
        final AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(SyncService.class);
        final SyncService bean = applicationContext.getBean(SyncService.class);
//        final SyncService bean = SpringContextHolder.getBean(SyncService.class);
        for (int i = 0; i < 100; i++) {
            bean.test(i);
        }
    }
}

service方法:

java 复制代码
package com.xxx.tmp;
import org.springframework.stereotype.Component;
@Component
public class SyncService {
    //    @Async
    public void test(final int i) {
        System.out.println(Thread.currentThread().getName() + "------" + i);
    }
}

配置:

java 复制代码
package com.xxx.tmp;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;


@Configuration
@EnableAsync
@ComponentScan("com.xxx.tmp")
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        final ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setMaxPoolSize(50);
        threadPoolTaskExecutor.setQueueCapacity(50);
        threadPoolTaskExecutor.setKeepAliveSeconds(1);
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(final Throwable throwable, final Method method, final Object... objects) {
                System.out.println("出现异常啦~~~~~~");
            }
        };
    }
}

就可以真实启动了,无须通过test去测试

相关推荐
java1234_小锋16 小时前
String、StringBuilder、StringBuffer的区别?
java·开发语言
星原望野16 小时前
JAVA集合:List、Set和Map
java·开发语言·list·set·map·集合
IT_陈寒16 小时前
React性能优化踩的坑,这个错你可能也会犯
前端·人工智能·后端
2601_9577875816 小时前
星链引擎矩阵系统:插件化多平台 API 网关与账号级隔离技术实践
java·矩阵·插件化架构
zhangxingchao16 小时前
AI应用开发三:RAG技术与应用
前端·人工智能·后端
多敲代码防脱发17 小时前
Spring进阶(容器实现)
java·开发语言·后端·spring
可视之道17 小时前
工业物联网前端技术栈选型与性能优化实战
后端
星辰_mya17 小时前
彩云之上——[特殊字符]的架构师
java·后端·微服务·面试·架构
phltxy17 小时前
Redis 主从复制
java·数据库·redis
Full Stack Developme17 小时前
Spring-Core 解析
java·spring·rpc