如果我添加@EnableJpaRepositories注释,服务类自动装配将返回Null

如果我在配置类中添加@EnableJpaRepositories批注,则服务类Autowire实例将变为空并抛出空指针异常,并且如果我删除了批注,则Autowire可以正常工作。

我得到了NullPointerException作为回报ajaxDemoService.getcountryList();控制器行。

如何解决此问题?

下面是我的配置代码。

 @Configuration
        @EnableWebMvc
        @ComponentScan(basePackages = {"com.advanced.controller","com.advanced.service","com.advanced.repository"})
        @EnableJpaRepositories(basePackages = {"com.advanced.repository"})
        public class WebConfig extends WebMvcConfigurerAdapter {
            @Bean
            public InternalResourceViewResolver resolver() {
                InternalResourceViewResolver resolver = new InternalResourceViewResolver();
                resolver.setViewClass(JstlView.class);
                resolver.setPrefix("/WEB-INF/view/");
                resolver.setSuffix(".jsp");
                return resolver;
            }

                @Override
                public void addResourceHandlers(ResourceHandlerRegistry registry) {
                    registry
                        .addResourceHandler("/resources/**")
                        .addResourceLocations("/resources/");
                }
            }

controller.java

 @Controller
    public class AjaxController {

        @Autowired
        AjaxDemoService ajaxDemoService;

        @RequestMapping(value = "/country",method = RequestMethod.GET)
        public @ResponseBody  List<Country> getallCountries() {
            return ajaxDemoService.getcountryList();
        }
    }

Service.java

public interface AjaxDemoService {

    public List<Country> getcountryList();

    public List<State> getStateList(int countryId) throws Exception;
}

ServiceImpl.java

@Service
public class AjaxDemoServiceImpl implements AjaxDemoService {

    @Autowired
    CountryRepository countryRepository;

    @Autowired
    StateRepository stateRepository;

    @Override
    @Transactional
    public List<Country> getcountryList() {
        return countryRepository.findAll();
    }

    @Override
    @Transactional
    @SuppressWarnings("unchecked")
    public List<State> getStateList(int countryId) throws Exception {
        return (List<State>) stateRepository.findById(countryId).orElseThrow(() -> new Exception("Resource Not Found"));
    }
}
i569546235 回答:如果我添加@EnableJpaRepositories注释,服务类自动装配将返回Null

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3153030.html

大家都在问