[英]Difference Between web-app's context-param and servlet's init-param?
I'm using Spring MVC. 我正在使用Spring MVC。 In a Controller class, I want to use the @Value annotation to inject a value that comes from a properties file:
在Controller类中,我想使用@Value批注注入来自属性文件的值:
@Value("${upload.dir}")
private String uploadDir;
So I need to put a property-placeholder somewhere. 所以我需要在某个地方放置一个占位符。
The web.xml is typical: web.xml是典型的:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/mvc-dispatcher-servlet.xml</param-value>
</init-param>
...
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/business-context.xml</param-value>
</context-param>
First, I put the placeholder in business-context.xml. 首先,我将占位符放在business-context.xml中。 It doesn't work: "Could not autowire field".
它不起作用:“无法自动连线字段”。
Then I put it in mvc-dispatcher-servlet.xml, it works. 然后我将其放在mvc-dispatcher-servlet.xml中,它可以工作。
So I'm confused about these two contexts, are they the same one or different? 因此,我对这两个上下文感到困惑,它们是相同还是不同? Because the beans I defined in business-content.xml can be autowired, but the @Value doesn't work.
因为我在business-content.xml中定义的bean可以自动装配,但是@Value不起作用。
I don't want to put the placeholder in both xml files 'cause I have a long 'location' property. 我不想将占位符放在两个xml文件中,因为我有一个长的“位置”属性。 Also the business-context.xml will be used by some jobs, so it cannot be omitted.
而且business-context.xml将被某些作业使用,因此不能省略。
Any way to make placeholder defined in business-context.xml become visible in mvc-dispatcher-servlet.xml as well? 有什么方法可以使在business-context.xml中定义的占位符在mvc-dispatcher-servlet.xml中也可见?
A BeanFactoryPostProcessor
which is what the property-placeholder is will only operate (and be visible) to the application context it is defined in. This is by design. 属性占位符所在的
BeanFactoryPostProcessor
仅在定义它的应用程序上下文中操作(并且是可见的)。这是设计使然。 So no you cannot make a property-placeholder from a parent visible to a child context (well with some nasty hacks you could). 因此,不能,您不能使父级的属性占位符对子级上下文可见(以及一些可能的讨厌的技巧)。
As a work around you could do the following in your business-context.xml 作为解决方法,您可以在business-context.xml中执行以下操作
<util:properties id="applicationProperties" location="path-to-your-very-long-location" />
<context:property-placeholder properties-ref="applicationProperties" />
and this in your mvc-dispatcher-servlet.xml. 这在您的mvc-dispatcher-servlet.xml中。
<context:property-placeholder properties-ref="applicationProperties" />
Define the same <context:property-placeholder ../>
in both xml context and simply reference the already loaded properties. 在两个xml上下文中定义相同的
<context:property-placeholder ../>
,并仅引用已加载的属性。 Added advantage the properties are only loaded once. 增加的优点是,属性仅加载一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.