是否可以在扩展另一个类的类中使用@Value
?
下面是相关的代码片段。在 Lo_Controller
类中它工作得很好,但在 Lo_DisplayHandler
中总是返回 null
。我能想到的唯一原因是因为它依赖于另一个类,而该类没有用 @Component
注释。如果这是原因,那么建议从类似于 @Value
的属性文件中读取值的选项是什么?
为了测试它,我在 Lo_DisplayHandler
中从 @Component
更改为 @Controller
来看看它们是否以某种方式与每个相关其他,但它也会返回 null
。
这有效:
package com.ma.common.controller;
imports ...
@Controller
@RequestMapping("/log")
public class Lo_Controller {
@Value("${log.display.lastpage}")
private String lastPageUrl;
...
这总是返回null
:
package com.ma.log.handler;
imports ...
@Component
public class Lo_DisplayHandler extends Lo_Handler {
public Lo_DisplayHandler() {
super();
}
@Value("${log.display.lastpage}")
private String lastPageUrl;
...
mvc-dispatcher-servlet.xml
<context:component-scan base-package="com.ma.common.controller, com.ma.log.handler" />
<context:property-placeholder location="classpath:restServices.properties"/>
<mvc:annotation-driven />
<mvc:resources mapping="/**" location="/" />
@Component
public class Lo_DisplayHandler extends Lo_Handler {
@Value("${log.display.lastpage}")
private String lastPageUrl;
public void anyOtherMethod(){
String _a = lastPageUrl; //FAIL - always null
}
@PostConstruct
public void initIt() throws Exception {
String _a = lastPageUrl; //OK - when the application is deployed and started for the first time
}
@PreDestroy
public void cleanUp() throws Exception {
String _a = lastPageUrl; //OK - when the application is stopped
}
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
最佳答案
这里三个可能的问题:
首先,我不鼓励扩展类,因为 Spring 可以更好地 Autowiring 依赖项。但它应该有效 其次,您必须关注 bean 的生命周期。该属性将在实例化后设置。 @PostConstruct 来验证内容。 第三,属性(property)所有者在等级背景下的可见性并不直接。因此,如果您在根 applicationContext 中定义 @value,则它不会由您的 DispatcherServlet 上下文设置。要测试它,请注入(inject)在根级别定义的 bean 的依赖项,您将看到您的 @Value 将被考虑在内。
lastPageUrl 属性可以从同一上下文中的 bean 访问(通过推送创建或拉取创建)。 在推送创建的情况下,如果另一个 bean Autowiring Lo_DisplayHandler bean 并调用您的方法 anyOtherMethod(),它将获取该值。
@Component
public class ScannableIntoYourContext{
@Autowired
private Lo_DisplayHandler myHandler;
}
另一种方法是从 ObjectFactory 中提取 bean。
@Autowired
private ObjectFactory<Lo_DisplayHandler> bean;
Lo_DisplayHandler instanceFromContext = bean.getObject();
关于java - @Value 不在扩展其他类的类中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27070823/