使用请求范围bean注入Spring Boot依赖项

时间:2016-12-09 21:30:34

标签: java spring web-services spring-mvc

我正在尝试依赖注入一个bean到另一个bean,但我想通过简单地自动装配到类中,而不是通过" @Configuration类"来实现。这是控制器类:

@Controller
public class RestfulSourceController {

    @Autowired
    Response response;

    @RequestMapping(value="/rest", method=RequestMethod.GET, produces="application/json")
    @ResponseBody
    public Object greeting() {
        return response.getResponse();
    }

}

以下是" @Configuration"每个

中声明了bean的类
@Configuration
class RequestConfigurationBeans {

    @Autowired
    private ServicesRepository servicesRepo;

    @Autowired
    private HttpServletRequest request;

    @Bean(name = 'requestServiceConfig')
    @Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.TARGET_CLASS)
    public ServiceModel requestServiceConfig(){
        String serviceName = RequestUtil.getServiceName(this.request)
        ServiceModel serviceModel = servicesRepo.findByName(serviceName)
        return serviceModel
    }

}

@Configuration
public class ServletFilterBeans {

    /* I don't want to autowire here, instead I want to autowire in the Response class directly, instead of passing the bean reference into the constructor
    @Autowired
    ServiceModel requestServiceConfig
    */

    @Bean
    @Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.TARGET_CLASS)
    public Response response(){
        return new Response(/*requestServiceConfig*/);
    }

}

最后这里是Response类:

class Response {

    //I want to Autowire the bean instead of passing the reference to the constructor
    @Autowired
    ServiceModel requestServiceConfig

    Object response

    public Response(/*ServiceModel requestServiceConfig*/){
        //this.requestServiceConfig = requestServiceConfig

        if (requestServiceConfig.getType() == 'rest'){
            this.response = getRestfulSource()
        }

    }


    private Object getRestfulSource(){
        RestTemplate restTemplate = new RestTemplate()
        String url = requestServiceConfig.sourceInfo.get('url')
        return restTemplate.getForObject(url, Object.class)
    }
}

然而,当我像这样设置依赖注入时,我得到一个空指针异常,因为autowired bean" requestServiceConfig"没有实例化。我如何通过autowiring依赖注入bean,以便我不必通过构造函数将引用传递给bean?

1 个答案:

答案 0 :(得分:0)

问题是在requestServiceConfig的构造函数中使用Response。自动装配只能在创建对象后进行,因此依赖关系在此处只能为空。

要解决此问题并能够使用自动装配,您可以将代码从构造函数移动到@PostConstruct生命周期方法:

@PostConstruct
private void init() {
    if ("rest".equals(this.requestServiceConfig.getType())) {
        this.response = getRestfulSource();
    }
}