弹簧启动依赖性注入请求示波器豆



我试图将一个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*/);
    }
}

最后是响应类:

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)
    }
}

但是,当我设置这样的依赖项注入时,我会得到一个空指针异常,因为自动bean" requestServiceConfig"未实例化。我如何依赖性将bean注入自动引导,以便我不必通过构造函数传递对bean的引用?

问题是在Response的构造函数中使用requestServiceConfig。自动性只能在对象创建之后发生,因此依赖关系只能在此处为null。

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

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

最新更新