首页 > 其他分享 >springboot通过注解Resource引用指定配置

springboot通过注解Resource引用指定配置

时间:2022-09-07 16:56:15浏览次数:73  
标签:return springboot service wxMessage Resource new 注解 null properties

yaml配置文件中增加两个不同环境的配置:

java配置文件,参考微信支付的代码:

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {
    private final WxMaProperties properties;

    private static Map<String, WxMaService> maServices;

    @Autowired
    public WxMaConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }

    @Bean
    @Primary
    public WxMaService getMaService() {
        WxMaService wxService = maServices.get(properties.getConfigs().get(0).getAppid());
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", properties.getConfigs().get(0).getAppid()));
        }

        return wxService;
    }

    @Bean(name = "test")
    public WxMaService getVendorMaService() {
        WxMaService wxService = maServices.get(properties.getConfigs().get(1).getAppid());
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", properties.getConfigs().get(0).getAppid()));
        }

        return wxService;
    }

    public static WxMaMessageRouter getRouter(String appid) {
        return routers.get(appid);
    }

    @PostConstruct
    public void init() {
        List<WxMaProperties.Config> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
        }

        maServices = configs.stream()
            .map(a -> {
                WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
                // 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常
                config.setAppid(a.getAppid());
                config.setSecret(a.getSecret());
                config.setToken(a.getToken());
                config.setAesKey(a.getAesKey());
                config.setMsgDataFormat(a.getMsgDataFormat());

                WxMaService service = new WxMaServiceImpl();
                service.setWxMaConfig(config);
                return service;
            }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
    }

    private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> {
        service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
            .templateId("此处更换为自己的模板id")
            .data(Lists.newArrayList(
                new WxMaSubscribeMessage.MsgData("keyword1", "339208499")))
            .toUser(wxMessage.getFromUser())
            .build());
        return null;
    };

    private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
        log.info("收到消息:" + wxMessage.toString());
        service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())
            .toUser(wxMessage.getFromUser()).build());
        return null;
    };

    private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {
        service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
            .toUser(wxMessage.getFromUser()).build());
        return null;
    };

    private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
        try {
            WxMediaUploadResult uploadResult = service.getMediaService()
                .uploadMedia("image", "png",
                    ClassLoader.getSystemResourceAsStream("tmp.png"));
            service.getMsgService().sendKefuMsg(
                WxMaKefuMessage
                    .newImageBuilder()
                    .mediaId(uploadResult.getMediaId())
                    .toUser(wxMessage.getFromUser())
                    .build());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return null;
    };

    private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
        try {
            final File file = service.getQrcodeService().createQrcode("123", 430);
            WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
            service.getMsgService().sendKefuMsg(
                WxMaKefuMessage
                    .newImageBuilder()
                    .mediaId(uploadResult.getMediaId())
                    .toUser(wxMessage.getFromUser())
                    .build());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return null;
    };

}

配置类:

 

 

初始化配置:

 

 

指定不同配置的service:

 

使用方法:

注入yaml第二个配置:

 

不指定名称就是第一个配置:

 

标签:return,springboot,service,wxMessage,Resource,new,注解,null,properties
From: https://www.cnblogs.com/stromgao/p/16666409.html

相关文章

  • springboot的日志配置
    转载:https://blog.csdn.net/tz845195485/article/details/123361895#========================logging日志相关的配置=====================#日志级别trace<debug<inf......
  • SpringBoot解决BigDecimal传到前端后精度丢失问题
    1、局部处理(1)在相应字段上加@JsonFormat@JsonFormat(shape=JsonFormat.Shape.STRING)(2)在相应字段上加@JsonSerialize@JsonSerialize(using=ToStringSerializer.class......
  • jackson 常用注解
    @JsonPropertyOrder({"name","id"})指定序列化属性的顺序@JsonPropertyOrder(alphabetic=true)按字母顺序对属性进行排序@JsonRawValue属性注释可以指示Jackso......
  • Description Resource Path Location Type Java compiler level does not match t
    问题:DescriptionResourcePathLocationTypeJavacompilerleveldoesnotmatcht今天在自己项目中整合HBaseAPI的时候遇到了这个问题,想了半天也不知道自己干了什么......
  • 类型注解基础
    介绍类型注解是一种给函数参数、返回值以及任何变量增加类型描述的技术,规范的注解可以大大提升代码可读性举个例子,下面的代码没有任何类型注解classDuck:"""鸭子类......
  • springboot集成hibernate-validator
    一、项目搭建1、使用springboot搭建一个web工程建web工程,不使用骨架创建maven的Java工程即可,不需要创建maven的web工程。2、添加父工程坐标和添加web启动器<parent>......
  • @Valid注解
    分类限制说明空和非空检查@Null限制只能为null@NotNull限制必须不为null@NotEmpty验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为......
  • SpringBoot使用自定义注解+AOP+Redis实现接口限流
    为什么要限流系统在设计的时候,我们会有一个系统的预估容量,长时间超过系统能承受的TPS/QPS阈值,系统有可能会被压垮,最终导致整个服务不可用。为了避免这种情况,我们就需要对......
  • SpringBoot常用注解
    SpringBoot常用注解1.@SpringBootApplicationspringBoot的基石,启动类@Configuration应许spring注册额外的bean或者导入其他配置类@EnableAutoConfiguration启用Sp......
  • Springboot定义全局异常类详解
    前言当我们在开发过程中,会因为一些异常程序出现500,如果直接显示给客户看,这样很不友好。并且对我们后期维护,排查bug很困难。准备1.创建一个SpringBoot项目,引入web依赖,......