如何将对象公开给我的所有Struts2视图? [英] How can I expose an object to all of my Struts2 views?
问题描述
我有一个Web应用程序,它使用带有Freemarker模板的Struts2和Spring4.
I have a web application using Struts2 with Freemarker templates, and Spring4.
我有一些配置字符串存储在.properties
文件中,我需要在每个页面上进行渲染(例如,我们的CDN路径,其中包含版本字符串).现在,这些属性由spring读取,并存储在org.springframework.core.env.Environment
的实例中.
I have a few configuration strings that are stored in a .properties
file which I need to render on every page (for example, our CDN path, which contains a version string). Right now these properties are read by spring and stored in an instance of org.springframework.core.env.Environment
.
是否有一种简单的方法可以使我的所有实例都可以访问我的Environment实例?我们还有另一个应用程序通过动作继承来执行此操作,其中基类具有getEnvironment()
方法.我不喜欢这种方法,因为每个操作都必须扩展基类.
Is there an easy way to make my Environment instance accessible to all of my views? We have another application which does this through action inheritance, where a base class has a getEnvironment()
method. I dislike this approach as every action must extend the base class.
推荐答案
将逻辑放入一个bean(例如Configuration.java)中,然后将其注入(通过Spring DI,Java EE CDI或其他方式)所有动作中需要它,并通过Getter公开.
Put your logic in a bean (eg. Configuration.java) that is then injected (through Spring DI, Java EE CDI, or whatever) in all the actions needing it, and exposed through a Getter.
但是我不会低估继承方法 此处 ,它并不像您描述的那样糟糕,因为您可以在遍历的同时构建添加规范的继承树它:一个BaseAction,一些Sub-BaseAction,一些子Sub ...等等.了解详情.
But I would not underestimate the inheritance approach here, it's not as bad as you're describing it, 'cause you can build your inheritance tree adding specification while traversing it: one BaseAction, some Sub-BaseActions, some sub-sub... etc. Read more.
如果以后发现同级BaseAction需要在BaseAction上放置某些内容,只需将其上移一个级别(在父BaseAction中,向上移动到每个人都通用的第一个).
If you discover later that something you've put on a BaseAction is needed by sibling BaseActions, just move it one level up (in a parent BaseAction, up to the first one, common to everyone).
这篇关于如何将对象公开给我的所有Struts2视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!