使用注解的 Servlet 初始化参数 [英] Servlet Initialization parameters using annotation

查看:33
本文介绍了使用注解的 Servlet 初始化参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Servlet 注释并遇到了这个片段

I am trying to learn Servlet annotations and came across this snippet

@WebServlet(urlPatterns="/MyPattern", initParams={@WebInitParam(name="ccc", value="333")})

这对我来说很有意义.但是,我不明白为什么不是这样

This makes sense to me. However, I don't understand why it is not like this

@WebServlet(urlPatterns="/MyPattern", initParams={(name="ccc", value="333"), (name="abc", value="1")})

所以,问题是当我们已经将属性声明为 initParams 时,为什么我们需要放置 @WebInitParam 注释.对我来说似乎是多余的,还是我遗漏了什么?

So, the question is why we need to put @WebInitParam annotation when we already declared the attribute as initParams. It seems redundant to me, or am I missing something?

推荐答案

对于大多数关于语言设计选择的问题,我们只能在这里推测.我认为这样做的一些原因是:

As with most questions about language design choices we can only speculate here. I think some reasons for this are:

  1. 保持语言简单.
    它有点多余,但注释的语法可以重用,不需要新的语言结构.这使得解析和阅读更容易.当然,它更长,但写注释的名称也更明确.

  1. Keeping the language simple.
    It is kind of redundant, but the syntax for annotations can be reused and does not require new language constructs. This makes it easier to parse and to read. Sure, It's longer, but it's also more explicit to write the annotation's name.

不要限制未来可能的语言增强.
如果注释支持继承,则建议的语法将不起作用.我不知道这是否是一个计划中的功能,但如果可以省略类型,就不可能直接实现它.

Don't restrict possible future language enhancements.
The proposed syntax would not work if annotations would support inheritance. I don't know if that's even a planned feature but it would not be possible to implement straightforward it if the type can be omitted.

在许多情况下,注释数组似乎是一种解决方法.在 Java 8 中可以避免这种情况,您可以在其中添加多个相同类型的注释:

In many cases an array of annotations seems like a workaround anyway. It can be avoided in Java 8, where you can add multiple annotations of the same type:

@WebServlet(urlPatterns="/MyPattern")
@WebInitParam(name="ccc", value="333")
@WebInitParam(name="abc", value="1")

(我不知道 servlet api 是否真的支持这个)

(I don't know if the servlet api actually supports this yet though)

这篇关于使用注解的 Servlet 初始化参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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