struts 2 - 我应该在哪里设置全局应用程序变量? [英] struts 2 - where should I set global application variables?

查看:40
本文介绍了struts 2 - 我应该在哪里设置全局应用程序变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 struts 2 并且我想读取一些自定义定义的参数(全局变量),最好是从 web.xml 或一些自定义的.properties"文件(即未在 Java 源代码中硬编码).这个问题在过去的半小时里一直让我发疯,因为我无法在谷歌上找到任何合理的解决方案.

I'm using struts 2 and I'd like to read some custom-defined parameters (global variables), preferably from web.xml or some custom ".properties" file (i.e. not hardcoded in the Java sources). This problem has been driving me mad for the past half hour as I can't google any reasonable solution.

这样做的最佳方法是什么?我觉得很奇怪,这太难了......

What is the best way to do this? I find it strange that it is so difficult ...

一切顺利

尼古拉·蒙泰奇奥

推荐答案

首先问问自己:这些常量真的与 Struts2 相关还是仅与您的应用程序相关?

Ask yourself first: are those constants really pertinent to Struts2 or just to your application ?

如果后者,这不是真正的 Struts2 问题,并且您-相信我-不想将您的常量"管理绑定到 Struts2(或 web.xml),则它们应该可以从您的 webapp 之外的应用程序代码访问(例如,来自一些测试代码).

If the later, this is not really a Struts2 question, and you -trust me- dont' want tie you "constants" management to Struts2 (or web.xml), they should be accesible from your application code outside the webapp (for example, from some testing code).

我知道您对某些(比如)Constants 类(带有静态 final 字段)中的硬编码"常量感到难过,但请注意,这可能不是那么糟糕的做法 - 如果它们是真正的常量,不太可能独立于您的 Java 代码进行更改.值得深思.

I understand that you feel bad about "harcoding" constants in some (say) Constants class (with static final fields), but be aware that this might not be so bad practice -if they are really constants, unlikely to be changed independently of your java code. Worth a thought.

如果没有,您可能需要一些 ConstantsManager 类,它可能是一个单例无状态对象(或某种服务"对象),它知道如何加载常量,例如从某些类路径中的属性文件.您的应用程序的对象(可能包括某些 Struts2 操作)如何获得对该 ConstantsManager 实例的引用?在最简单(也是最脏)的实现中,您将拥有一个带有静态 getInstance() 方法的单例模式实现.更灵活、更时尚的是DI/IOC方式,也许带有一些 bean 容器,如 Spring;而 Struts2 非常适合使用 那个.如果您不熟悉这些概念,它们肯定会很快出现,用于处理与访问某些常量类似(但不那么琐碎)的问题.

If not, you might need some ConstantsManager class, which might be a singleton stateless object (or some kind of 'Service' object), which knows how to load the constants, for example from some property file in the classpath. How do the objects of your application (including perhaps some Struts2 action) get a reference to that ConstantsManager instance? In the simplest (and dirtiest) implementation, you'd have a Singleton pattern implementation with a static getInstance() method. More flexible and fashionable is the DI/IOC way, perhaps with some beans container, as Spring; and Struts2 is well suited to play with that. And if you're not familiar with this concepts, they will surely pop up soon, for issues similiar (but less trivial) that accessing some constants.

这篇关于struts 2 - 我应该在哪里设置全局应用程序变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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