關於controller呼叫controller/service呼叫service/util呼叫service/websocket中autowired的解決方法
阿新 • • 發佈:2018-12-17
問題背景
這個問題,其實分為四個問題,思路是一致的。
- controller呼叫controller
- service呼叫service
- util呼叫service
- websocket中autowired
呼叫實戰
例如我現在有個AppConfig,需要在EmailUtil裡面呼叫
@Component @Data @ConfigurationProperties(prefix = "system") // 接收application.yml中的myProps下面的屬性 public class AppConfig { public String filepath; public String urlpath; }
然後EmailUtils中定義一個靜態的AppConfig
@Component public class EmailUtil { @Autowired public static AppConfig appConfig; public static void sendActiveEmail(String toEmail,String checkCode,HttpServletRequest request){ EmailUtil.sendEmail(toEmail,"iXXX啟用郵件", "您正在進行iXXX賬號認證,請點選該連結啟用:"+appConfig.getUrlpath()+"/xxxx/active/"+toEmail+"/"+checkCode+" 。如非本人操作,請忽略該資訊。"); } }
然後隨便定義一個config,或者找到之前已經定義的,追加以下set程式碼
@Configuration
public class ConfigurationFilter{
@Autowired
public void setAppConfig(AppConfig appConfig){
EmailUtil.appConfig=appConfig;
}
}
這樣就完成了,傳送的時候可以成功獲取對應的值,不會發生NullPointException。
WebSocket注入@[email protected]
在WebSocket也是這樣注入,因 SpringBoot+WebSocket 對每個客戶端連線都會建立一個 WebSocketServer(@ServerEndpoint 註解對應的) 物件,Bean 注入操作會被直接略過,因而手動注入一個全域性變數
@ServerEndpoint("/im/{userId}/{toUserId}")
@RestController
public class ImController {
public static ChatMessageRepository chatMessageRepository;
//......
}
可以配置在WebSocketConfig裡面
/**
* 開啟WebSocket支援
* @author zhengkai
*/
@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter 用於掃描和註冊所有攜帶 ServerEndPoint 註解的例項,
* 若部署到外部容器 則無需提供此類。
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
/**
* 因 SpringBoot WebSocket 對每個客戶端連線都會建立一個 WebSocketServer(@ServerEndpoint 註解對應的) 物件,Bean 注入操作會被直接略過,因而手動注入一個全域性變數
*
* @param messageService
*/
@Autowired
public void setMessageService(ChatMessageRepository chatMessageRepository) {
ImController.chatMessageRepository = chatMessageRepository;
}
}