[英]Java REST web service constructor
Is there any point in having a constructor in a Java Web Service class? 在Java Web Service类中使用构造函数有什么意义吗? (There seems to be no consensus in the articles I have found so far.)
(到目前为止我发现的文章似乎没有达成共识。)
I am using Jersey to implement a REST web service that needs to have a non-static common object (a string-processing utility class) made available to various (non-static) methods of the service. 我使用Jersey来实现一个REST Web服务 ,该服务需要有一个非静态公共对象(一个字符串处理实用程序类),可用于服务的各种(非静态)方法。
Initializing this common object would typically happen in the constructor of the class, if that were not a web service. 初始化此公共对象通常会在类的构造函数中发生,如果它不是Web服务的话。 But what about now that it is?
但是现在怎么样呢?
If a constructor cannot be used, should I put, in every relevant method, a synchronized block that checks whether the common object is available and, if not, initialize it? 如果不能使用构造函数,我是否应该在每个相关方法中放置一个同步块来检查公共对象是否可用,如果没有,则初始化它? Or is there a better approach?
还是有更好的方法?
Every web service class does have a constructor. 每个Web服务类确实有一个构造函数。 If you don't include one then Java automatically adds the default no-arg constructor for you.
如果您不包含一个,那么Java会自动为您添加默认的no-arg构造函数。 You can:
您可以:
Try @PostConstruct annotation. 尝试@PostConstruct注释。 It might help you.
它可能对你有帮助。
It's just an opinion, but if you want to adhere 100% to REST your web service should be stateless. 这只是一个意见,但如果你想100%坚持REST,你的网络服务应该是无国籍的。 Initializing common objects in web service method calls implies state so it's not the best idea.*
在Web服务方法调用中初始化公共对象意味着状态,因此这不是最好的主意。*
*this is debatable, as can be seen in comments. *这是有争议的,可以在评论中看到。 However any synchronization and shared object initialization if not necesarry IMO should be a no-no in REST applications.
但是,任何同步和共享对象初始化(如果不是必需的IMO)应该是REST应用程序中的禁忌。
Contructor certainly is a solution, even better one would be to use dependency injection and inject the object you need to your webservice instance at creation. Contructor当然是一个解决方案,更好的方法是使用依赖注入并在创建时将您需要的对象注入Webservice实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.