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去测试

相关推荐
Aision_3 小时前
从工具调用到 MCP、Skill完整学习记录
java·python·gpt·学习·langchain·prompt·agi
zc.z7 小时前
JAVA实现:纯PCM格式音频转换成BASE64
java·音视频·pcm
mask哥8 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
无风听海8 小时前
深入剖析 YARP 的 Transforms:构建灵活的反向代理转换管道
后端·中间件·asp.net
Gopher_HBo8 小时前
负载均衡
后端
自由生长20248 小时前
RAG已死?什么标题党啊!
后端
Aaswk9 小时前
Java Lambda 表达式与流处理
java·开发语言·python
是宇写的啊9 小时前
Spring AOP
java·spring
万邦科技Lafite9 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
东方小月9 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构