【任务标题】
静态方法中使用spring管理的bean
【状态】
已解决
【任务奖励】
银币 * 2
【要求时间】
1 Day
【委托人】
村民C
【任务详情】
请提供方法能够在静态方法中调用被spring容器管理的类
【承接人】
konb
【解决过程】
如下代码示例,解决的步骤如下
- 添加一个当前类的静态属性
serverManager
- 添加要使用的被spring管理的对象属性
messageService
- 创建被
@PostConstruct
修饰的initServerManager()
方法,对serverManager
对象赋值,值(this
)为当前类被new
后的对象
- 调用需要的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| package com.spm.study.demoproject.area.soft.server;
import com.alibaba.fastjson.JSON; import com.spm.study.demoproject.area.soft.Service.basic.NormalMessageService; import com.spm.study.demoproject.area.soft.Service.notice.MessageService; import com.spm.study.demoproject.area.soft.entity.T_USER; import com.spm.study.demoproject.area.soft.entity.basic.NormalMessage; import com.spm.study.demoproject.area.soft.entity.notice.ChangeBatch; import com.spm.study.demoproject.area.soft.entity.notice.Message; import com.spm.study.demoproject.area.soft.util.SessionUtil; import com.spm.study.demoproject.area.soft.util.basic.MessageEnum; import com.spm.study.demoproject.area.soft.util.manual.ManualConstant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
@Component public class ServerManager {
@PostConstruct public void initServerManager() { serverManager = this; } @Autowired private MessageService messageService;
@Autowired private NormalMessageService normalMessageService;
private static Map<Integer, WebSocketServer> servers = new ConcurrentHashMap<>();
public static ServerManager serverManager;
public static void broadCast(String msg){
}
public static int getTotal(){ return servers.size(); } public static Map<Integer, WebSocketServer> getServers(){ return servers; } public static void sendNoticeInformation(Integer userId, String message, ChangeBatch changeBatch) { WebSocketServer webSocketServer = servers.get(userId); Message msg = new Message(); msg.setContent(message); msg.setToUser(userId); msg.setBatch(changeBatch.getBatch()); msg.setCid(changeBatch.getId()); serverManager.messageService.save(msg); if (webSocketServer != null) { webSocketServer.sendMessage(message); }
} public static void remove(WebSocketServer server) { servers.remove(server.getUserId()); } public static void remove(Integer userId) { servers.remove(userId); }
public static boolean isOnline(Integer userId) { return servers.get(userId) != null; }
}
|