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

问题描述 投票:0回答:1

这是配置类中的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类。即使bean在AppRestTemplate bean之前被实例化(我通过在配置类中放置调试点来检查它),我将自动装配的“applicationPropertiesDataService”bean作为null

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

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

java spring dependency-injection
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.