@async多线程自动装配

话不多说,直接看代码,注解已经描述很清晰。

package achun.spring.assist.config;

import achun.spring.assist.dto.AchunDes;
import achun.spring.assist.dto.IConst;
import achun.spring.assist.source.PropertyUtil;
import achun.spring.assist.source.StrUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

@AchunDes("@async异步注解多线程配置(开关)")
public class ScheduleConfigCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        boolean b = false;
        String type = PropertyUtil.getStringConfig(IConst.项目插件);
        if(StrUtil.isNotBlankOrNull(type)){
            for(String s:type.split("@@")){
                if("schedule".equalsIgnoreCase(s)){
                    b = true;
                    break;
                }
            }
        }
        return b;
    }
}
package achun.spring.assist.config;
import achun.spring.assist.dto.AchunDes;
import achun.spring.assist.source.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

@AchunDes("@async异步注解多线程配置")
@Conditional(value=ScheduleConfigCondition.class)
@Configuration
@EnableAsync
public class ScheduleConfig implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger("AChunLog");
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(ThreadUtil.getSchedule(10));
        logger.info("==========@@@ ScheduleConfig start successfully @@@==========");
    }
}

注:如下方式会使@Async失效

1、异步方法使用static修饰

2、异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类

3、异步方法不能与异步方法在同一个类中

4、类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象

5、如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解

6、在Async 方法上标注@Transactional是没用的。 在Async 方法调用的方法上标注@Transactional 有效。

7、调用被@Async标记的方法的调用者不能和被调用的方法在同一类中不然不会起作用!!!!!!!

8、使用@Async时要求是不能有返回值的不然会报错的 因为异步要求是不关心结果的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九零互联网

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值