[英]Why injecting inner-class into another inner-class in the same outer-class does not work?
我有一個類里面有兩個內部類。 我用@Service注釋了外部類,用@Component注釋了兩個內部類。 InnerClassA @Autowired到OuterClass,InnerClassB @Autowired到InnerClassA。 即使所有三個bean都已初始化,但InnerClassA中的innerClassB為null。
@Service
public class ChatService{
@Autowired
private ChatServerUtils chatServerUtils;
@Autowired
private PushNotificationHelper pushNotificationHelper;
@Component
public class PushNotificationHelper{
@Autowired
private ChatServerUtils chatServerUtils; //this is null
@Autowired
private PushService pushService;
@Async
public void sendPushNotifications(Group group){
Map<String, Integer> notificationData= new HashMap<>();
Map<String, CompletableFurure<Integer>> unreadCountFutures = new ArrayList<>();
for(Member member : group){
CompletableFurure<Integer> unreadCountFuture = chatServerUtils.getUnreadCount(group, member);
unreadCountFutures.put(member.getId(), unreadCountFuture);
}
for(Map.Entry<String, CompletableFurure<Integer>> entry : unreadCountFutures.entrySet()){
notificationData.put(entry.getKey(), entry.getValue().get());
}
pushService.sendNotifications(notificationData);
}
}
@Component
public class ChatServerUtils{
@Async
public CompletableFuture<Integer> getUnreadCount(Group group, Member member){
...
}
}
}
更多信息:外部課程是一種聊天服務,可處理與聊天用戶,消息和群組相關的內容。 還有另一項服務可以發送推送通知。 當消息發送到組時,我必須向組中的所有用戶發送推送通知。 在發送推送通知服務請求之前,我必須聯系外部聊天服務器並獲取每個組成員的未讀消息計數。 聊天服務器的API不支持在單個呼叫中獲取所有用戶的未讀計數。 由於這是一個耗時的過程,我需要異步進行。 這就是為什么我必須將這些方法移動到單獨的類中(使用@Async)。 除了ChatServiceUtil類中顯示的方法之外,PushNotificationHelper和ChatService都使用了更多方法。
如何使用外部ChatService
類中的chatServerUtils
變量? 由於PushNotificationHelper
由ChatService
封裝, ChatService
它應該可以訪問私有變量。
除此之外,我仍然沒有看到你的代碼從這個內部/外部類構造中受益的原因。 你說你有兩個內部類從你的外部類使用的方法,但是如果你將外部類注入它們,這些內部類仍然可以使用這些方法。 對我而言,您似乎應該仔細查看代碼的架構,並重新考慮其中的一些。 如果你不想這樣做,我希望我的上述建議有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.