gpt4 book ai didi

java - Spring Bean在配置类中初始化后仍然为null

转载 作者:行者123 更新时间:2023-12-02 11:51:56 25 4
gpt4 key购买 nike

这是我在配置类中的 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 类。我将 Autowiring 的“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;
}

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

最佳答案

您手动调用new AppRestTemplate();,这会绕过CDI(上下文和依赖注入(inject))。要获得 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;
}
}

关于java - Spring Bean在配置类中初始化后仍然为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47827498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com