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

相关推荐
小松学前端3 分钟前
第六章 7.0 LinkList
java·开发语言·网络
Wx-bishekaifayuan10 分钟前
django电商易购系统-计算机设计毕业源码61059
java·spring boot·spring·spring cloud·django·sqlite·guava
customer0814 分钟前
【开源免费】基于SpringBoot+Vue.JS周边产品销售网站(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·java-ee·开源
全栈开发圈16 分钟前
新书速览|Java网络爬虫精解与实践
java·开发语言·爬虫
WaaTong18 分钟前
《重学Java设计模式》之 单例模式
java·单例模式·设计模式
面试鸭20 分钟前
离谱!买个人信息买到网安公司头上???
java·开发语言·职场和发展
小白冲鸭1 小时前
【报错解决】使用@SpringJunitConfig时报空指针异常
spring·java后端开发