This question already has answers here:
How does autowiring work in Spring?
                                
                                    (9个答案)
                                
                        
                                3年前关闭。
            
                    
我想在FcSolrServiceImpl类中使用@autowire SolrCrudRepository,但它提供了NPE。以下是我的实现。

FcSolrServiceImpl.java

public class FcSolrServiceImpl<K> {

    @Autowired(required = true)
    SolrCrudRepository<K, String> repository;

    public void saveProduct(K input) {
        repository.save(input);  // Getting null pointer in repository
    }
}


产品.java

@SolrDocument(solrCoreName = "core1")
public class Product {

    Product() {
    };

    @Field
    @Id
    private String id;

    // getter setter hashcode equals toString methods

}


FcIndexSyncApplication.java

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class FcIndexSyncApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(FcIndexSyncApplication.class, args);
        FcSolrServiceImpl<Product> fpsi = new FcSolrServiceImpl<Product>();

        Product input = new Product();
        input.setID("abc");

        fpsi.saveProduct(input);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(FcIndexSyncApplication.class);
    }

    @Bean
    public SolrTemplate solrTemplate() throws Exception {
        HttpSolrServer httpSolrServer = new HttpSolrServer("${spring.data.solr.host}");
        return new SolrTemplate(httpSolrServer, "core1");
    }

}

最佳答案

您正在使用FcSolrServiceImpl创建newFcSolrServiceImpl<Product> fpsi = new FcSolrServiceImpl<Product>();

这样,Spring对该对象一无所知。您必须从Spring上下文中获取Bean,才能使用依赖项注入:

ApplicationContext ctx = SpringApplication.run(FcIndexSyncApplication.class, args);
FcSolrServiceImpl myBean = ctx.getBean(FcSolrServiceImpl.class);
myBean....

10-05 21:46