首页 > 解决方案 > 服务类的@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

标签: javaspringspring-mvcspring-boot

解决方案


这是null因为这个@Configuration类还定义了一个BeanDefinitionRegistryPostProcessor强制上下文在很早的时候创建那个 bean。

因为您正在使用字段注入,所以上下文必须解析AppServicebean,但它还不能,因为必须先应用后处理器。

您的配置看起来非常复杂,因此您可能需要稍微简化一下:

  • 将低级基础设施配置与主要配置分开
  • 始终将此类后处理器定义为public static方法,以便上下文可以调用@Bean方法而无需先构造类。

推荐阅读