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

相关推荐
Z_z在努力2 分钟前
【杂类】Spring 自动装配原理
java·spring·mybatis
程序员爱钓鱼14 分钟前
Go语言实战案例-开发一个Markdown转HTML工具
前端·后端·go
小小菜鸡ing30 分钟前
pymysql
java·服务器·数据库
getapi32 分钟前
shareId 的产生与传递链路
java
桦说编程42 分钟前
爆赞!完全认同!《软件设计的哲学》这本书深得我心
后端
thinktik1 小时前
还在手把手教AI写代码么? 让你的AWS Kiro AI IDE直接读飞书需求文档给你打工吧!
后端·serverless·aws
我没想到原来他们都是一堆坏人2 小时前
(未完待续...)如何编写一个用于构建python web项目镜像的dockerfile文件
java·前端·python
沙二原住民2 小时前
提升数据库性能的秘密武器:深入解析慢查询、连接池与Druid监控
java·数据库·oracle
mabo_9704@163.com2 小时前
SpringAI调用MCP服务的实现思路
spring·ai