在配置类中初始化后,Spring Bean仍为null

时间:2017-12-15 07:16:07

标签: java spring dependency-injection

这是配置类中的bean定义。

@Bean(name = "applicationPropertiesDataService")
public com.ing.app.data.ApplicationPropertiesDataService 
applicationPropertiesDataService() {
    return new com.ing.app.data.ApplicationPropertiesDataService();
}

这是我使用上述bean的类的bean定义。

@Bean(name = "appRestTemplate")
public AppRestTemplate appRestTemplate() {
    return new AppRestTemplate();
}

这是AppRestTemplate类。我正在获得autowired" applicationPropertiesDataService" bean为null,即使bean在AppRestTemplate bean之前被实例化(我通过在配置类中放置一个调试点来检查它)

import org.springframework.web.client.RestTemplate;

import com.ing.app.data.ApplicationPropertiesDataService;
import com.ing.app.interceptor.LoggingClientHttpRequestInterceptor;

public class AppRestTemplate extends RestTemplate {

@Autowired
private ApplicationPropertiesDataService applicationPropertiesDataService;

public AppRestTemplate() {

    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setOutputStreaming(false);
    BufferingClientHttpRequestFactory bufferingClientHttpRequestFactory =
        new BufferingClientHttpRequestFactory(requestFactory);
    this.setRequestFactory(bufferingClientHttpRequestFactory);

    if (isLoggingEnabled()) {

    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoggingClientHttpRequestInterceptor());
        this.setInterceptors(interceptors);
    }
}
}

private boolean isLoggingEnabled() {
    boolean isLoggingEnabled = false;
    Optional<ApplicationProperties> applicationProperties = applicationPropertiesDataService.findByCategoryAndName(
        Constant.APPLICATION_PROPERTIES_CATEGORY_AUDIT_LOGGING, Constant.APPLICATION_PROPERTIES_AUDIT_LOGGING);

    if (applicationProperties.isPresent()) {
        isLoggingEnabled = Constant.CONSTANT_Y.equalsIgnoreCase(applicationProperties.get().getValue());
    }
    return isLoggingEnabled;
}

我无法弄清楚,为什么autowired applicationPropertiesDataService bean为null。任何帮助,将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

您手动调用new AppRestTemplate();,绕过CDI(上下文和依赖注入)。要获得Autowired,Spring必须创建bean,而不是你。

有很多解决方案。你可以这样做:

@Bean(name = "appRestTemplate")
public AppRestTemplate appRestTemplate(ApplicationPropertiesDataService applicationPropertiesDataService) {
    return new AppRestTemplate(applicationPropertiesDataService);
}

public class AppRestTemplate extends RestTemplate {

    private final ApplicationPropertiesDataService applicationPropertiesDataService;

    @Autowired
    public AppRestTemplate(ApplicationPropertiesDataService applicationPropertiesDataService) {
        this.applicationPropertiesDataService = applicationPropertiesDataService;
    }
}
相关问题