gpt4 book ai didi

java - Spring 注入(inject)失败?

转载 作者:行者123 更新时间:2023-11-30 08:10:22 26 4
gpt4 key购买 nike

我有这个代码:

    private ServiceLayer serviceLayer;  
@RequestMapping(value = { "/process" }, method = RequestMethod.GET)
public String processMessaging(HttpServletRequest request)
{
return serviceLayer.getMd5Hash();

}

服务层

@Autowired
public ServiceLayer() {
}

问题是,当我运行项目时,Md5Hash 为空,serviceLayer 实例也为空,似乎没有调用 Constructor。

当我改用下面的代码时,它工作正常:

@Autowired
private ServiceLayer serviceLayer;

ServiceLayer 使用 @Component 注释。

然后 serviceLayer 的实例不为 null 但 md5Hash 为 null。我最近学习了 Spring Injections 的概念,但它没有按预期工作。有人请告诉我该怎么办?

已编辑

它在我创建 Property Autowired 而不是构造函数时运行。但是为什么它不能与使用或不使用 init() 方法 Autowiring 的构造函数一起工作。

我尝试按照“Link”的建议将 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;

}

在 Controller 中

@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文件中声明

关于java - Spring 注入(inject)失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31746010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com