Spring Boot Dependecy注射

时间:2018-06-12 07:30:47

标签: java spring spring-boot

 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.

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

从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/