spring 如果我在Sping Boot 应用程序中使用HTTP接口,业务逻辑应该在哪里?

gmxoilav  于 2023-09-29  发布在  Spring
关注(0)|答案(1)|浏览(80)

我有一个任务和条件:该服务应在HTTP接口接收数据,将其存储在SQL数据库中,并通过HTTP接口使其可用。如果我理解正确,那么在我的服务层中,我应该使用@HttpExchange,@GetExchange等。注解。在我看到的所有youtube视频中,所有人都写了一个没有业务逻辑的封闭服务,并将此逻辑放在控制器部分。使用HTTP接口的正确方法是什么?还是将业务逻辑放在服务层更合适?
我的服务

@HttpExchange("/transactions")
public interface TransactionClient {
    @GetExchange
    List<Transaction> findAll();

    @GetExchange("/{id}")
    Transaction findOne(@PathVariable Integer id);

    @PostExchange
    ResponseEntity<HttpStatus> saveTransaction(@RequestBody Transaction transaction);

    @PatchExchange("/{id}")
    void updateTransaction(@RequestBody Transaction transaction, @PathVariable Integer id);

    @DeleteExchange("/{id}")
    void deleteTransaction(@PathVariable Integer id);
}

我的控制器

@RestController
@Transactional(readOnly = true)
@RequestMapping("/transactions")
public class TransactionController {
    private final TransactionRepository transactionRepository;

    @Autowired
    public TransactionController(TransactionRepository transactionRepository) {
        this.transactionRepository = transactionRepository;
    }

    @GetMapping
    public List<Transaction> findAll() {
        return transactionRepository.findAll();
    }

    @GetMapping("/{id}")
    public Transaction findOne(@PathVariable("id") Integer id) {
        return transactionRepository.findById(id).orElse(null);
    }

    @Transactional
    @PostMapping
    public ResponseEntity<HttpStatus> saveTransaction(@RequestBody Transaction transaction) {
        transaction.setDateOfTransaction(new Timestamp(System.currentTimeMillis()));
        transactionRepository.save(transaction);
        return ResponseEntity.ok(HttpStatus.OK);
    }

    @Transactional
    @PatchMapping("/{id}")
    public void updateTransaction(@RequestBody Transaction transaction, @PathVariable("id") Integer id) {
        Transaction transactionFromDb = transactionRepository.findById(id).orElse(null);
        transaction.setId(id);
        transaction.setDateOfTransaction(transactionFromDb.getDateOfTransaction());
        transactionRepository.save(transaction);
    }

    @DeleteMapping("/{id}")
    @Transactional
    public void deleteTransaction(@PathVariable("id") Integer id) {
        transactionRepository.deleteById(id);
    }
}

我在youtube上看了很多视频,但是他们把逻辑放在控制器里,对吗?

o4hqfura

o4hqfura1#

如果你有很多业务逻辑,我建议你使用@Service类,而不是把所有东西都放在@Controller类中。然后,您可以将@Service类注入到控制器中,并调用@Service类上的方法。
控制器类:

@RestController
@AllArgsConstructor
@RequestMapping(value = "api")
public class TestResource {
    private final TestService testService;
   
    @GetMapping(value = "test")
    public ResponseEntity<String> test(
            Principal principal
    ) {
        testService.test();
        return ResponseEntity.noContent().build();
    }
}

服务等级:

@Service
public class TestService {

    public void test() {
      // do something here …
    }

}

相关问题