弹簧注射失败了吗?

时间:2015-07-31 12:17:02

标签: java spring spring-mvc

我有这段代码:

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

    }

服务层

@Autowired
    public ServiceLayer() {
    }

问题在于,当我运行项目时,Md5Hash为空,serviceLayer实例也为空,似乎没有调用构造函数。

当我使用以下代码时,它可以正常工作:

@Autowired
    private ServiceLayer serviceLayer;

ServiceLayer使用@Component.

进行注释

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

被修改

当我使用Property Autowired而不是构造函数时,它会运行。但是为什么它不能使用或不使用init()方法使用Constructor自动装配。

我尝试将md5Hash方法作为Bean作为" Link"建议,但这会引发另一个错误。

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;

2 个答案:

答案 0 :(得分:2)

init()中初始化的Md5Hash可能超出范围。更好的策略是拥有类似的东西

@Component
public class ServiceLayer() {

    @Autowired
    private String md5Hash;

    // Some other code
}

然后通过

声明一个bean
@Bean
public String md5Hash() {
    // Some code
    return md5HashString;
}

在某个@Config文件中声明

答案 1 :(得分:1)

我认为当你使用@Autowired时,这不会在param中用HttpServletRequest调用你的构造函数。

调用默认构造函数。您可以在init方法上使用@PostConstruct注释。

@Component
public class ServiceLayer {
    @PostConstruct
    public void init() {
      // set your md5
    }
  ...
}

进入你的控制器只需保持

@Autowired
private ServiceLayer serviceLayer;

这将创建并初始化您的ServiceLayer,您的控制器将使用Bean ServiceLayer进入您的控制器