无法在特定服务类中自动装配存储库

时间:2016-02-09 17:04:01

标签: java spring spring-mvc spring-data autowired

由于某些未知原因,在编写了一些新代码后,我无法自动导入导致Date = Now - 7 days的存储库。一切都工作得很好,但不知从哪里停止。从那以后我一直无法解决这个问题。

重要的是autowired停止在这个特定的服务类中工作,除了它工作得很好。

控制器类:

NullPointerException

服务类:

@Controller
public class AccountController {

    /**
     *  Display account page based on given module and action. 
     * 
     * @param aModule Account module
     * @param aAction Module action
     * @param principal Logged user
     * @return ModelAndView instance with required objects
     * @throws podraza.piotr.eshopper.exception.NotFoundException
     */
    @RequestMapping(value = "/account/{module}/{action}", method = RequestMethod.GET)
    public ModelAndView displayAccount(
            final @PathVariable("module") String aModule, 
            final @PathVariable("action") String aAction,
            final Principal principal) throws NotFoundException {

        if(aModule == null || aAction == null) {
            throw new NotFoundException();
        }

        final Module module;
        final Action action;

        try {
            module = Module.valueOf(aModule.toUpperCase());
            action = Action.valueOf(aAction.toUpperCase());
        } catch(RuntimeException ex) {
            throw new NotFoundException();
        }

        switch(module) {
            case USER:
                throw new NotFoundException();
            case ITEMS:
                switch(action) {
                    case NEW:
                        return prepareItemNew();
                    case MANAGER:
                        return prepareItemManager();
                    default:
                        throw new NotFoundException();
                }
            case SHOPPING:
                switch(action) {
                    case BIDS:
                        return prepareShoppingBids(principal);
                    default:
                        throw new NotFoundException();
                }
            default:
               throw new NotFoundException();
        }

    }

    /**
     * 
     * @return
     * @throws UserNotFoundException 
     */
    @RequestMapping(value = "/account", method = RequestMethod.GET) 
    public String displayShoppingBids() throws UserNotFoundException {
        return "redirect:/account/shopping/bids";
    }

    /**
     * 
     * @param form
     * @param result
     * @param request
     * @param errors
     * @param session
     * @param principal
     * @return 
     */
    @RequestMapping(value = "/account/item/new", method = RequestMethod.POST)
    public ModelAndView processCreatingNewItem(
            final @ModelAttribute("newItemForm") @Validated NewItemForm form,
            final BindingResult result, 
            final WebRequest request, 
            final Errors errors, 
            final HttpSession session,
            final Principal principal) {

        LOGGER.debug("Proccessing creating new item. Given form: " + form);

        ModelAndView mv = new ModelAndView("redirect:/account/items/manager");

        if(result.hasErrors()) {
            Set errorCodes = new HashSet();

            for(ObjectError error : result.getAllErrors()) {
                errorCodes.add(error.getCode());
            }

            mv.addObject("errorCodes", errorCodes);
            mv.setViewName("account-items-new");

            return mv;
        }

        accountService.addNewItem(form, principal);

        return mv;
    }

    /**
     * Prepare ModelAndView instance with containing required objects
     * to perform action of adding new item. 
     * @return ModelAndView instance with required models.
     */
    private ModelAndView prepareItemNew() {
        return new ModelAndView("account-items-new")
                .addObject("newItemForm", new NewItemForm())
                .addObject("formCategories", accountService.getCategoriesForNewItemForm());
    }

    /**
     * 
     * @return 
     */
    private ModelAndView prepareItemManager() {
        return new ModelAndView("account-items-manager");
    }

    /**
     * 
     * @param principal
     * @return
     * @throws UserNotFoundException 
     */
    private ModelAndView prepareShoppingBids(final Principal principal) throws UserNotFoundException {
        ModelAndView mv = new ModelAndView("account-shopping-bids");
        mv.addObject("bids", accountService.getUserBids(principal.getName()));
        return mv;
    }

    /**
     * 
     */
    private enum Module {

        USER, 
        ITEMS, 
        SHOPPING

    }

    /**
     * 
     */
    private enum Action {

        MESSAGES, 
        SUBSCRIPTIONS, 
        PASSWORD, 
        NEW, 
        MANAGER,
        BIDS

    }

    @Autowired
    private AccountService accountService;

    private static final Logger LOGGER = Logger.getLogger(AccountController.class);

}

@Service @Transactional(rollbackFor = Exception.class) public class AccountService { /** * * @param username * @return */ @Transactional(readOnly = true) public final List<BidDto> getUserBids(final String username) { LOGGER.debug("Fetching bids for user: " + username); final User user = userRepository.findByAccountLogin(username); final List<Bid> userBids = user.getBids(); return prepareUserBids(userBids); } /** * * @return */ @Transactional(readOnly = true) public final List<Category> getCategoriesForNewItemForm() { return categoryRepository.findCategoriesWithoutParent(); } /** * * @param form * @param principal */ public final void addNewItem(final NewItemForm form, final Principal principal) { final Auction auction = auctionConverter.convertToEntity(form); final Item item = auction.getItem(); final User owner = userRepository.findByAccountLogin(principal.getName()); item.setOwner(owner); itemRepository.save(item); } /** * Convert entity bid objects into DTOs and shorten auction names. * @param bids * @return */ private List<BidDto> prepareUserBids(final List<Bid> bids) { final List<BidDto> bidsDto = new ArrayList<>(); for(Bid bid : bids) { BidDto bidDto = bidConverter.convertToDto(bid); String auctionName = bidDto.getAuction().getName(); if(auctionName.length() > BIDS_AUCTION_MAX_LENGTH) { String shortenName = auctionName.substring(0, BIDS_AUCTION_MAX_LENGTH) + "..."; bidDto.getAuction().setName(shortenName); } bidsDto.add(bidDto); } return bidsDto; } private static final int BIDS_AUCTION_MAX_LENGTH = 25; private static final Logger LOGGER = Logger.getLogger(AccountService.class); @Autowired private UserRepository userRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private ItemRepository itemRepository; @Autowired private BidConverter bidConverter; @Autowired private AuctionConverter auctionConverter; } UserReporitory都没有自动装配,并且都抛出CategoryRepository

存储库:

NullPointerException

堆栈追踪:

@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface UserRepository extends JpaRepository<User, Long> {

    public User findByAccountLogin(final String login);

    public User findByAccountLoginOrAccountEmail(final String login, final String email);

    @Query("SELECT u FROM User u WHERE UPPER(u.account.login) LIKE UPPER('%'||:phrase||'%')")
    public List<User> findUsersByPhrase(final @Param("phrase") String phrase);

}


@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface CategoryRepository extends JpaRepository<Category, Long> {

    /**
     * Looking for categories with that has no subcategories.
     * @return list of categories
     */
    @Query("SELECT c FROM Category c WHERE parent_id IS NULL ORDER BY c.id")
    public List<Category> findMainCategories();

    /**
     * Looking for categories with given url value.
     * @param url
     * @return Category with given name
     */
    public Category findByUrl(final String url);

    /**
     * Looking for categories without parent category.
     * @return 
     */
    @Query("SELECT c FROM Category c WHERE parent_id IS NOT NULL")
    public List<Category> findCategoriesWithoutParent();

    public Category findByName(final String name);

}

任何想法可能导致这个问题?如果需要,我很乐意提供任何进一步的信息。

提前致谢。

0 个答案:

没有答案