java - 服务类的@autowired 注释在@configure 类spring boot 中不起作用
问题描述
当我使用@autowire 在配置类中注入我的依赖项时,它给我一个空值,请参考下面的代码。
@Configuration
public class DataSourceConfig {
@Autowired
AppService appService;
@Bean
public BeanDefinitionRegistryPostProcessor beanPostProcessor() {
return new BeanDefinitionRegistryPostProcessor() {
public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
}
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanRegistry) throws BeansException {
createBeans(beanRegistry);
}
};
}
private void createBeans(BeanDefinitionRegistry beanRegistry,DataSourceConfigService ds) {
appService.getDbDetails();
appService 在这里为空,如果我将使用这种方式调用它 BeanDefinitionRegistryPostProcessor beanPostProcessor(AppService
appService) 然后在 AppServiceImpl 类 AppDao 依赖项将为空
}
}
//// Service
@Service
public class AppServiceImpl implements AppService{
@Autowired
AppDao ds;
@Override
public List<A> getDatabaseConfiguration() {
return ds.getDbDetails(); // here ds is null
}
}
//dao
@Repository
public class AppDaoImpl implements AppDao {
@Qualifier("nameParamJdbcTemplate")
@Autowired
public NamedParameterJdbcTemplate nameParamJdbcTemplate;
@Override
public List<A> getDbDetails() {
return nameParamJdbcTemplate.query(SELECT_QUERY, new DataSourceMapper()); // nameParamJdbcTemplate is null
}
// datasource config
@Configuration
public class DataSourceBuilderConfig {
@Bean(name = "dbSource")
@ConfigurationProperties(prefix = "datasource")
@Primary
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "nameParamJdbcTemplate")
@DependsOn("dbSource")
@Autowired
public NamedParameterJdbcTemplate jdbcTemplate1(@Qualifier("dbSource") DataSource dbSource) {
return new NamedParameterJdbcTemplate(dbSource);
}
}
我想要的是当我的 beanPostProcessor() 被执行时,我希望我所有的依赖 bean 都应该被实例化,即
@Autowired
AppService appService;
@Autowired
AppDao ds;
@Qualifier("nameParamJdbcTemplate")
@Autowired
public NamedParameterJdbcTemplate nameParamJdbcTemplate;
I am new to spring so any help or working examples would be great. Thanks
解决方案
这是null
因为这个@Configuration
类还定义了一个BeanDefinitionRegistryPostProcessor
强制上下文在很早的时候创建那个 bean。
因为您正在使用字段注入,所以上下文必须解析AppService
bean,但它还不能,因为必须先应用后处理器。
您的配置看起来非常复杂,因此您可能需要稍微简化一下:
- 将低级基础设施配置与主要配置分开
- 始终将此类后处理器定义为
public static
方法,以便上下文可以调用@Bean
方法而无需先构造类。
推荐阅读
- python - Docker build pytest:无法建立新连接:[Errno 111] Connection denied
- reactjs - 选择字段未填充 从 Redux 表单中的下拉数组中选择值
- python - 纪元纳秒到正常时间
- speech-recognition - 有什么方法可以提高 Pocketsphinx 在语音识别方面的准确性吗?
- javascript - Metamask 仅在页面刷新后注入 web3
- node.js - Dialogflow NodeJs Fulfillment V2 - webhook 方法调用在完成回调之前结束
- c# - itextsharp:如何在 C# 中将 DataGridView (Templatefield) 导出为 PDF?
- xamarin.forms - 如何在 Xamarin 表单中实现可扩展和可折叠的底栏?
- typescript - 在运算符中使用的 Typescrtip 字符串文字类型
- swift - 如何从 Swift 中的 jsonobject 获取 key:value?