1. 程式人生 > >spring靜態類注入

spring靜態類注入

建立XmppMessageUtil類

    static Logger logger = LoggerFactory.getLogger(XmppMessageUtil.class);

    private static XmppMessageUtil xmppMessageUtil;

    @Resource(name = "loadBalanced")
    private RestTemplate loadBalanced;
使用 @PostConstruct註解( @PostConstruct說明 被@PostConstruct修飾的方法會在伺服器載入Servlet的時候執行,並且只會被伺服器呼叫一次,類似於Serclet的inti()方法。
被@PostConstruct修飾的方法會在建構函式之後,init()方法之前執行

public static void sendXmppMessage(String userFromId, String password, String userId, XmppMessageBody body) {
        try {
            body.setTimeSend(new Date());
            Map<String, Object> mapPara = new HashMap<String, Object>();
            mapPara.put("userId", userId);
            mapPara.put("body", JSON.toJSONString(body));
            mapPara.put("userFromId", userFromId);
            mapPara.put("password", password);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
            com.yhyt.health.spring.AppResult result = xmppMessageUtil.loadBalanced
.postForObject("http://dialog/dialog/sendMessage?userId={userId}&body={body}", httpEntity, com.yhyt.health.spring.AppResult.class, mapPara); if (null != result && "200".equals(result.getStatus().getCode())) { logger.info("推送下線成功"); } } catch (Exception e) { logger.error("傳送xmpp失敗,使用者id"+userId,e); } }