zoukankan      html  css  js  c++  java
  • Spring异步执行(@Async)2点注意事项

      Spring中可以异步执行代码,注解方式是使用@Async注解。

      原理、怎么使用,就不说了。


      写2点自己遇到过的问题。

    1.方法是公有的

      // 通知归属人
    @Async
    public void notifyPusher(Project project) {

         

          }


    2.异步代码,需要放在外部单独的类中。

       @Service("asyncBiz")
    public class AsyncBiz {

        

    @Async
    public void notifyPusher(Project project) {

         

           }


     据说这是一个“常识”,外部方法才会被Spring拦截器拦截到额。


    代码调用示例

    @Service
    public class ProjectServiceImpl implements ProjectService{
    
    public void audit(long id, short status) {
    		
    			if(project.getPusher() != null){
    				AsyncBiz asyncBiz = SpringContextUtil.asyncBiz();
    				asyncBiz.notifyPusher(project);
    				asyncBiz.notifyCare(project);
    			}
    		
    	}
    
    }


    一个工具类

    @Component
    public class SpringContextUtil implements ApplicationContextAware{
    
    	private static ApplicationContext ctx;
    	@Override
    	public void setApplicationContext(ApplicationContext applicationContext)
    			throws BeansException {
    		this.ctx = applicationContext;		
    	}
    	
    	public static ApplicationContext getCtx(){
    		return ctx;
    	}
    	
    	public static Object getBean(String name) throws BeansException { 
            return ctx.getBean(name); 
    	} 
    	
    	public static AsyncBiz asyncBiz() throws BeansException { 
            return (AsyncBiz) ctx.getBean("asyncBiz"); 
    	} 
    
    }

    可以灵活手动获得Spring容器中的bean,也可以很好地解决循环依赖问题。


  • 相关阅读:
    C#调用Exe文件的方法及如何判断程序调用的exe已结束(转)
    C# Color (转)
    【666】语义分割减少过拟合
    【665】构建多损失函数
    libc timer
    分支管理
    MULLS:论文阅读
    微信支付宝整合支付开发中的常见问题
    IIS8中安装和使用URL重写工具(URL Rewrite)的方法
    通过Java 技术手段,检查你自己是不是被绿了...
  • 原文地址:https://www.cnblogs.com/qitian1/p/6462669.html
Copyright © 2011-2022 走看看