配置类
@Configuration
@ComponentScan("demo")
@EnableAsync
public class Config implements AsyncConfigurer{
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(26);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
服务层
@org.springframework.stereotype.Service
public class Service {
@Async
public void task(Integer i){
System.out.println("异步"+i);
}
@Async
public void task1(Integer i){
System.out.println("2异步"+i);
}
}
测试层
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(
Config.class);
Service s = annotationConfigApplicationContext.getBean(Service.class);
for (int i = 0; i < 10; i++) {
s.task(i);
s.task1(i);
}
}
}
结果
异步1
异步0
异步3
2异步0
异步4
2异步4
异步5
2异步5
异步6
2异步6
异步7
2异步7
异步8
2异步8
异步9
2异步9
2异步3
2异步2
2异步1
异步2
读取属性文件,配置类型安全的bean
@Component
@ConfigurationProperties(prefix="book",location={"classpath:config/book.properties"})
restful API
获取请求路径中?后面的参数@RequestParam("id")
获取路径中/1/的1 @PathVariable
网友评论