【问题标题】:Spring Boot Dependecy injectionSpring Boot 依赖注入
【发布时间】:2018-11-21 12:31:01
【问题描述】:
 package com.elsoproject;

    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Component;

@Component
@Scope("session")

public class SpyGirl {

    public String iSaySomething() {
        return "spicy vagyok";
    }

}



package com.elsoproject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {


    @Autowired
    private SpyGirl spicey;


    @RequestMapping("/")
    public String index() {
        return spicey.iSaySomething();
    }

}

例外:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'spicey'; nested exception is org.springframework.beans.factory.BeanCreationException:

 Error creating bean with name 'spyGirl': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; 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.

【问题讨论】:

  • 问题是什么?
  • 你用的是spring-boot吗?
  • 如果您提出具体问题并仔细格式化您的问题以便它们实际上是可读的,您可能会发现它更容易

标签: java spring spring-boot


【解决方案1】:

从 SpyGirl 组件中删除 @Scope("session")。在创建会话之前无法对其进行初始化。

public interface ISpyGirl {
    String iSaySomething();
}


@Component
public class SpyGirl implements ISpyGirl {

    @Override
    public String iSaySomething() {
        return "spicy vagyok";
    }
}



 @RestController
public class DemoController {
    @Autowired
    private ISpyGirl spicy;


    @RequestMapping("/spicy")
    public String index() {
        return spicy.iSaySomething();
    }

}

请阅读这篇文章以获取更多信息。 https://tuhrig.de/making-a-spring-bean-session-scoped/

【讨论】:

    【解决方案2】:

    SpyGirl bean 的作用域是会话作用域。它不存在于会话之外,因此您不能在非会话范围的 HomeController 中使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-05
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-20
      • 2012-12-23
      • 1970-01-01
      相关资源
      最近更新 更多