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

相关推荐
小七rrrrr4 分钟前
动态规划法 - 53. 最大子数组和
java·算法·动态规划
1024小神11 分钟前
Oracle Free 实例重装系统操作指南
后端
bug在路上11 分钟前
在swoole中使用mysql连接池
后端
我是哪吒11 分钟前
分布式微服务系统架构第165集:阿里,字节,腾讯架构经验汇总
后端·面试·github
似水流年流不尽思念11 分钟前
transient关键字有什么作用?
后端·面试
福大大架构师每日一题11 分钟前
2025-08-18:最大化游戏分数的最小值。用go语言,给你一个长度为 n 的数组 points 和一个整数 m。另有一个大小为 n 的数组 gameScor
后端
自由的疯12 分钟前
在 Java IDEA 中使用 DeepSeek 详解
java·后端·架构
花酒锄作田15 分钟前
KRaft部署单点三实例Kafka集群
后端