gpt4 book ai didi

java - Spring 国际奥委会 : What about serialization?

转载 作者:搜寻专家 更新时间:2023-11-01 03:14:50 29 4
gpt4 key购买 nike

我正在开发一个涉及 Spring 框架的新软件组件。我喜欢它,但现在我有一个关于 IoC 和序列化的问题。

假设我有这个类(省略了导入和包声明):

public class EMailNotificationEndpoint implements NotificationEndpoint {
private List<String> notficationEmailAdresses = new ArrayList<String>();
transient private MailSender mailSender;

public EMailNotificationEndpoint(MailSender mailSender) {
this.mailSender = mailSender;
}

@Override
public void notify(Notification notification) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(notficationEmailAdresses.toArray(new String[notficationEmailAdresses.size()]));
simpleMailMessage.setSubject(notification.getType().toString());
simpleMailMessage.setText(notification.getMessage());

mailSender.send(simpleMailMessage);
}
}

NotificationEndpoint 扩展了 Serializable 以确保所有实现都是可序列化的。关键是我无法序列化 MailSender(即 org.springframework.mail.MailSender BTW)并希望它在反序列化时注入(inject)。现在我的问题很明显:我可以这样做吗?如果答案是肯定的:如何?

我可以自由地更改接口(interface)和实现,所以应该有办法处理这样的事情,即使这意味着我必须重构相关类。

非常感谢任何想法或提示!

最佳答案

关于将其设为 transient ,您是正确的。

您需要做的就是在反序列化时根据需要恢复它。

您可以实现适当的 readObject 方法来进行初始化:

     /**
* Always treat de-serialization as a full-blown constructor, by
* initializing or validating the final state of the de-serialized object.
*/
private void readObject(ObjectInputStream aInputStream)
throws ClassNotFoundException, IOException {
//always perform the default de-serialization first
aInputStream.defaultReadObject();
//do your other stuff, like initialization
this.mailSender = ...
}

Note: Here, the object itself has to get the MailSender implementation, which is not very DI (Dependency Injection). Either you are ok with that, or you find another way (tipically another object is involved after deserialization, and sets the correct dependency).


如果您真的喜欢进行依赖注入(inject),我找到了 Spring 和 Entities 的链接,其中可能包含适用于这种情况的常识:
http://chris-richardson.blog-city.com/migrating_to_spring_2_part_3__injecting_dependencies_into_en.htm

关于java - Spring 国际奥委会 : What about serialization?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1427486/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com