Spring中@Async用法总结

本文总结了Spring中@Async的使用,包括@Async注解的声明、配置、无返回值和返回值的调用方式,以及异常处理和事务处理机制。通过@Async,可以在独立线程中执行方法,提高应用程序的并发性能。
摘要由CSDN通过智能技术生成

1、@controller 控制器(注入服务)
2、@service 服务(注入dao)
3、@repository dao(实现dao访问)
4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的)
@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。
下面写这个是引入component的扫描组件

其中base-package为需要扫描的包(含所有子包)
1、@Service用于标注业务层组件
2、@Controller用于标注控制层组件(如struts中的action)
3、@Repository用于标注数据访问组件,即DAO组件.
4、@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Service public class UserServiceImpl implements UserService { }
@Repository public class UserDaoImpl implements UserDao { } getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“*”) 这样来指定,这种bean默认是单例的,如果想改变,可以使用@Service(“beanName”)
@Scope(“prototype”)来改变。可以使用以下方式指定初始化方法和销毁方法(方法名任意): @PostConstruct public void init() { }

使用前
1.声明

@EnableAsync
@Component
@Lazy(false)
public class AsyncTask {
   
    private static final Logger logger = LoggerFactory.getLogger(AsyncTask.class);
    @Autowired
    private AutoAllocateCaseJob autoAllocateCaseJob;
    @Autowired
    private ColService colService;
    public AsyncTask(){
        logger.info("task初始化");
    }
    @Async
    public void startAllocateCaseJob(){
        autoAllocateCaseJob.execute();
    }
    @Async
    public Future<ReminderUserDetailRtnModel> queryCurrentPayables(UserDetailReq userDetailReq){
        AsyncResult<ReminderUserDetailRtnModel> result=null;
        try{
        ReminderUserDetailRtnModel reminderUserDetailRtn = colService.queryReminderUserDetail(userDetailReq);
            result=new AsyncResult<ReminderUserDetailRtnModel>(reminderUserDetailRtn);
        }catch(Exception e){
            logger.error("错误",e);
        }
        return result;
    }
}

@Lazy(false)立即加载 @Lazy(true)延迟加载,用到才加载

2.在applicationContext.xml中加入到扫描包里面确保能扫描到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值