servlet中的参数化构造函数 [英] Parameterized constructor in servlet

查看:141
本文介绍了servlet中的参数化构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在servlet中声明参数化构造函数,它只是构造函数吗?

Can I declare parameterized constructor inside servlet which is only constructor ?

如果不是,那么为什么?

If no then why ?

推荐答案

否。

Servlet实例是由容器通过反射创建的,他们期望找到一个公共的,无arg的构造函数(默认构造函数)。

Servlet instances are created by the container via reflection, and they expect to find a public, no-arg constructor (the default constructor).

要配置servlet,请使用web.xml文件中指定的servlet参数。这些传递给你的servlet的 init() 方法。

To configure your servlet, use servlet parameters specified in the web.xml file. These are passed to your servlet's init() method.

虽然servlet容器选择非默认构造函数并将字符串强制转换为简单类型并且反射性地调用构造函数是可能,但这不是Servlet规范所要求的。

While it would be possible for a servlet container to choose a non-default constructor and coerce character strings to simple types and invoke the constructor reflectively, this isn't what the Servlet specification requires.

部分原因可能是历史性的; servlet首先在依赖注入系统使这种替代方案广泛实施之前很早就被指定。但是,这样的构造函数相当有限;传递可以从web.xml中指定的简单字符串创建的参数是可行的,但是更有用的对象—例如— DataSource 会很尴尬。

Part of the reason may be historical; servlets were first specified long before dependency injection systems made this alternative widely practiced. However, such constructors would be fairly limited; it would be practical to pass arguments that can be created from a simple character string specified in the web.xml, but more useful objects—a DataSource, for example—would be awkward.

虽然在servlet中有最终成员变量会很好。

It would be nice to have final member variables in a servlet though.

JSR以前称为WebBeans(我认为JSR 299)将为Servlet中的依赖注入支持提供一些标准。这可能会解决当前方法中的一些缺点。

The JSR formerly known as "WebBeans" (JSR 299, I think), will provide some standards for dependency injection support in Servlets. This might address some of the drawbacks in the current approach.

这篇关于servlet中的参数化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆