如何在Spring Boot中自动装配组件中的存储库接口

时间:2018-11-01 07:48:58

标签: java spring spring-boot

我正在使用Spring + Mysql,并且可以成功地自动将PagingAndSortingRepository<T,E>类中从RepositoryRestController扩展的类自动连接。

我可以在下面的contoller中自动连接我的存储库。

包com.fallavi.api.user.controller;

import com.fallavi.api.MyConfig;
import com.fallavi.api.purchase.model.Purchase;
import com.fallavi.api.purchase.repository.PurchaseRepository;
import com.fallavi.api.reader.model.Reader;
import com.fallavi.api.reader.repository.ReaderRepository;
import com.fallavi.api.user.calculator.UserCreditHelper;
import com.fallavi.api.user.exceptions.UserCanNotFindException;
import com.fallavi.api.user.model.UserCreditEnoughModel;
import com.fallavi.api.user.model.UserCreditModel;
import com.fallavi.api.user.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@RepositoryRestController
@RequestMapping("/user")
public class UserCreditController {

    @Autowired
    private ReaderRepository readerRepository;

    @Autowired
    private UsersRepository usersRepository;

    @Autowired
    private PurchaseRepository purchaseRepository;

    @GetMapping(
            value = "/userHasCreditEnough/{reader_id}",
            headers = "Content-Type=application/json")
    public ResponseEntity<UserCreditEnoughModel> userHasCreditEnough(
            @RequestHeader(value = "Authorization") String token,
            @PathVariable Long reader_id) {

        UserCreditHelper userCreditHelper = new UserCreditHelper();

        // Find user ID from authorization code START //
        Long userID = usersRepository.getUserIDByAuthToken(token);
        if (userID == null) {
            throw new UserCanNotFindException();
        }
        // Find user ID from authorization code END //

        // Find user credit START //
        List<Purchase> purchaseList = this.purchaseRepository.findByUserID(userID);
        Integer userCreditLeft = userCreditHelper.userCreditLeft(purchaseList);
        // Find user credit END //

        // Find user's credit left for Reader START //
        Reader reader = this.readerRepository.findByReaderID(reader_id);
        boolean isUserCreditEnough = userCreditHelper.userHasCreditEnough(userCreditLeft, reader);
        // Find user's credit left for Reader END //

        return ResponseEntity.ok(new UserCreditEnoughModel(isUserCreditEnough, reader.getOnline()));
    }
}

当然,我想将所有层分离为服务,存储库和控制器,这就是为什么我创建一个新的帮助器类即服务层的原因。

@Service
public class UserCreditHelper {

   @Autowired
   UsersRepository usersRepository;

   ....some methods...
}

为了调用UserCreditHelper类,我在下面的控制器类示例中使用ApplicationContext

@RepositoryRestController
@RequestMapping("/user")
public class UserCreditController {

    @Autowired
    private ReaderRepository readerRepository;

    @Autowired
    private UsersRepository usersRepository;

    @Autowired
    private PurchaseRepository purchaseRepository;

    @GetMapping(
            value = "/userHasCreditEnough/{reader_id}",
            headers = "Content-Type=application/json")
    public ResponseEntity<String> userHasCreditEnough(
            @RequestHeader(value = "Authorization") String token) {

        // com.fallavi.api.user.calculator is the package of UserCreditHelper.
        ApplicationContext ctx = new AnnotationConfigApplicationContext( "com.fallavi.api.user.calculator" );

        return ResponseEntity.ok("test");
    }
}

当我尝试请求/userHasCreditEnough/{reader_id}端点时,它始终会显示错误。

"Error creating bean with name 'userCreditHelper': Unsatisfied dependency expressed through field 'usersRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fallavi.api.user.repository.UsersRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}",

1 个答案:

答案 0 :(得分:1)

您应该创建一个接口,它将成为您的服务层。然后将该接口注入控制器,并在控制器的期望端点中调用期望方法。从那里,从这个注入的接口调用您想要的植入。