在静态类使用非静态方法,利用注解@Component将工具类实例化到spring容器中

首先说下遇到的问题:

要在项目中集成极光推送第三方工具,所以使用了工具类。工具类一般都使用的是静态方法static修饰,但是第三方工具需要使用appKey和masterSecret.我们将这两个数据灵活放在支撑平台,所以需要实时获取这两个数据。

@component (把普通pojo实例化到spring容器中,相当于配置文件中的 

泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。

 被@controller 、@service、@repository 、@component 注解的类,都会把这些类纳入进spring容器中进行管理

下面贴上极光推送工具类代码,项目使用的是maven,首先需要导入maven依赖.

        
         
            cn.jpush.api
            jpush-client
            3.3.9
        
        
            cn.jpush.api
            jiguang-common
            1.1.1
        

然后是极光推送工具类代码

package 自己的包;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;


@Component//此注解将工具类注入spring
public class JiGuangPushUtil {
    //两个参数分别填写你申请的masterSecret和appKey
//    private static String  appKey = "93c5f73197595dbd3f822d15";
//    private static String masterSecret = "535bf8de8450c4f8d5168dad";
    private static String  appKey;
    private static String masterSecret;
    private static RemoteBasicConfigService remoteBasicConfigService;

    @Autowired
    public void setRemoteBasicConfigService(RemoteBasicConfigService remoteBasicConfigService){
        JiGuangPushUtil.remoteBasicConfigService = remoteBasicConfigService;
}
    private void utilsnit () {//将非静态变量赋值到静态变量
        String appKey2 = remoteBasicConfigService.getValue("appKey");
        String masterSecret2 = remoteBasicConfigService.getValue("masterSecret");
        appKey = appKey2;
        masterSecret = masterSecret2;
    }
//    private static JPushClient jPushClient=new JPushClient(masterSecret, appKey);

    /**
     * 通知推送
     * 备注:推送方式不为空时,推送的值也不能为空;推送方式为空时,推送值不做要求
     * @param type 推送方式:1、“tag”标签推送,2、“alias”别名推送
     * @param value 推送的标签或别名值
     * @param alert 推送的内容
     */
    public static void pushNotice(String type, String value, String alert){
        //静态方法调用非静态方法
        JiGuangPushUtil jiGuangPushUtil = new JiGuangPushUtil();
        jiGuangPushUtil.utilsnit();

        Builder builder= PushPayload.newBuilder();
        builder.setPlatform(Platform.all());//设置接受的平台,all为所有平台,包括安卓、ios、和微软的
        /*builder.setNotification(Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(alert)
                        .setBadge(+1)//设置iOS角标+1
                        .setSound("happy")//设置声音
                        .build())
                .build());*/
        //设置如果用户不在线、离线消息保存的时间
        Options options=Options.sendno();
        options.setTimeToLive(86400l);    //设置为86400为保存一天,如果不设置默认也是保存一天

        builder.setOptions(options);
        //设置推送方式
        if(type.equals("alias")){
            builder.setAudience(Audience.alias(value));//根据别名推送
        }else if(type.equals("tag")){
            builder.setAudience(Audience.tag(value));//根据标签推送
        }else{
            builder.setAudience(Audience.all());//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到
        }
        //设置为采用通知的方式发送消息
        builder.setNotification(Notification.alert(alert));

        /*builder.setNotification(Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(alert)
                        .disableBadge()
//                        .setBadge(+1)//设置iOS角标+1
                        .setSound("happy")//设置声音
                        .build())
                .build());*/

        Message.Builder newBuilder=Message.newBuilder();
        HashMap map = new HashMap<>();
        map.put("state","tapeout");//这里设置APP一个账户只能在一台设备上登录用的
        newBuilder.setMsgContent(alert).addExtras(map);//消息内容

//        newBuilder.setMsgContent(alert).addExtra("EXTRA_EXTRA", "past");

        Message message=newBuilder.build();
        builder.setMessage(message);

        PushPayload pushPayload=builder.build();

        JPushClient jPushClient=new JPushClient(masterSecret, appKey);

        try{
            //进行推送,实际推送就在这一步
            PushResult pushResult=jPushClient.sendPush(pushPayload);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 自定义消息推送
     * 备注:推送方式不为空时,推送的值也不能为空;推送方式为空时,推送值不做要求
     * @param type 推送方式:1、“tag”标签推送,2、“alias”别名推送
     * @param value 推送的标签或别名值
     * @param alert 推送的内容
     */
    public static void pushMsg(String type, String value,String alert){
        //静态方法调用非静态方法
        JiGuangPushUtil jiGuangPushUtil = new JiGuangPushUtil();
        jiGuangPushUtil.utilsnit();

        Builder builder= PushPayload.newBuilder();
        builder.setPlatform(Platform.all());//设置接受的平台
        if(type.equals("alias")){
            builder.setAudience(Audience.alias(value));//别名推送
        }else if(type.equals("tag")){
            builder.setAudience(Audience.tag(value));//标签推送
        }else{
            builder.setAudience(Audience.all());//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到
        }
        Message.Builder newBuilder=Message.newBuilder();
        HashMap map = new HashMap<>();
        map.put("fl","ok");
        newBuilder.setMsgContent(alert).addExtras(map);//消息内容

        newBuilder.setMsgContent(alert).addExtra("cs", "past");

        Message message=newBuilder.build();
        builder.setMessage(message);
        PushPayload pushPayload=builder.build();

        JPushClient jPushClient=new JPushClient(masterSecret, appKey);

        try{
            PushResult pushResult=jPushClient.sendPush(pushPayload);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void SendPush(String  obj, String DeviceSN, String MsgType) {
        //静态方法调用非静态方法
        JiGuangPushUtil jiGuangPushUtil = new JiGuangPushUtil();
        jiGuangPushUtil.utilsnit();

        JPushClient jPushClient = new JPushClient(masterSecret, appKey);
//        String objStr = ObjectToJson(obj);
        String objStr = "";
        PushPayload push = PushPayload.newBuilder().setPlatform(Platform.all())
                .setMessage(Message.newBuilder().setMsgContent(objStr)
                        .addExtras(Collections.singletonMap("MsgType", MsgType)).build())
                .setAudience(Audience.alias(DeviceSN)).build();
        PushResult result = null;
        try {
            result = jPushClient.sendPush(push);
            /*LOG.info("Got result - " + result);
            LOG.info("send objStr - " + objStr);
            System.out.println(result);
            System.out.println(objStr);*/
        } catch (Exception e) {
           /* LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + push.getSendno());*/
        }
        /*} catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + push.getSendno());
        }*/
        /*if (result == null) {
            throw new APIException("与设备通话失败,请联系管理员处理!");
        }
        return result;*/
    }

    public static void pushMessageNotice(String type, String value, String alert){
        //静态方法调用非静态方法
        JiGuangPushUtil jiGuangPushUtil = new JiGuangPushUtil();
        jiGuangPushUtil.utilsnit();

        Builder builder= PushPayload.newBuilder();
        builder.setPlatform(Platform.all());//设置接受的平台,all为所有平台,包括安卓、ios、和微软的
        //设置如果用户不在线、离线消息保存的时间
        Options options=Options.sendno();
        options.setTimeToLive(86400l);    //设置为86400为保存一天,如果不设置默认也是保存一天

        builder.setOptions(options);
        //设置推送方式
        if(type.equals("alias")){
            builder.setAudience(Audience.alias(value));//根据别名推送
        }else if(type.equals("tag")){
            builder.setAudience(Audience.tag(value));//根据标签推送
        }else{
            builder.setAudience(Audience.all());//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到
        }
        //设置为采用通知的方式发送消息
        builder.setNotification(Notification.alert(alert));

        Message.Builder newBuilder=Message.newBuilder();
        HashMap map = new HashMap<>();
        map.put("aaa","bbb");
        newBuilder.setMsgContent(alert).addExtras(map);//消息内容

//        newBuilder.setMsgContent(alert).addExtra("EXTRA_EXTRA", "past");

        Message message=newBuilder.build();
        builder.setMessage(message);

        PushPayload pushPayload=builder.build();

        JPushClient jPushClient=new JPushClient(masterSecret, appKey);

        try{
            //进行推送,实际推送就在这一步
            PushResult pushResult=jPushClient.sendPush(pushPayload);
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    /*public static void main(String[] args){
        //给标签为kefu的用户进行消息推送
        JiGuangPushUtil.pushNotice("tag","kefu","你有新的任务,请及时处理");
    }*/

    public JiGuangPushUtil() {
        super();
    }
}

只作为参考,代码可以直接使用.

你可能感兴趣的:(在静态类使用非静态方法,利用注解@Component将工具类实例化到spring容器中)