Spring Boot 依赖注入
Posted
技术标签:
【中文标题】Spring Boot 依赖注入【英文标题】:Spring Boot Dependecy injection 【发布时间】: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吗? 如果您提出具体问题并仔细格式化您的问题以便它们实际上是可读的,您可能会发现它更容易 【参考方案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 中使用它。
【讨论】:
以上是关于Spring Boot 依赖注入的主要内容,如果未能解决你的问题,请参考以下文章
spring-boot-test spyBean 注解不注入依赖
在依赖注入环境(如 Spring Boot)中创建设计模式是不是无用?
Kotlin Spring Boot 单元测试 - 添加 @TestExecutionListeners 不会注入依赖项