我有以下代码:
private ServiceLayer serviceLayer;
@RequestMapping(value = { "/process" }, method = RequestMethod.GET)
public String processMessaging(HttpServletRequest request)
{
return serviceLayer.getMd5Hash();
}
服务层
@Autowired
public ServiceLayer() {
}
问题是,当我运行项目时,
Md5Hash
为null,而serviceLayer
实例也为null,似乎没有调用Constructor。当我改用以下代码时,它可以正常工作:
@Autowired
private ServiceLayer serviceLayer;
ServiceLayer用
@Component.
注释那么
serviceLayer
的实例不为空,但md5Hash
为null。我最近了解了Spring Injections
的概念,但是它没有按预期工作。有人告诉我该怎么办?已编辑
它在我使属性自动装配而不是构造函数时运行。但是为什么它不能与通过init()方法自动装配的构造方法一起使用。
我尝试按照“链接”的建议将md5Hash方法制作为Bean,但这使我陷入另一个错误。
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String com.orange.raidar.backend.controller.raidarDummyController.md5Hash; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getMD5hash' defined in class path resource [com/orange/raidar/backend/filter/ServiceLayer.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.lang.String]: Factory method 'getMD5hash' threw exception; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
我现在尝试的是:
@Bean
public String mD5Hash() {
md5Hash = MD5Generator.getMd5HashCode(httpRequestToString());
return md5Hash;
}
并在控制器中
@Autowired
private String md5Hash;
最佳答案
init()中初始化的Md5Hash可能超出范围。更好的策略是拥有这样的东西
@Component
public class ServiceLayer() {
@Autowired
private String md5Hash;
// Some other code
}
然后通过声明一个bean
@Bean
public String md5Hash() {
// Some code
return md5HashString;
}
在某些
@Config
文件中声明