我创建了这个代码结构。它越来越不通用。
我寻找编写更通用的代码。
我的所有 Controller 都应该有一个 save、get、getById
如何拥有更通用的 Controller ?, 如何传递服务对象,是否需要传递
对于其他层,如果您认为这可能更通用......请不要犹豫
@RequestMapping(value = "/rest")
@RestController
public class CardsRestController extends BaseController {
private final CardsService cardsService;
@Autowired
public CardsRestController(final CardsService cardsService) {
this.CardsService = cardsService;
}
@GetMapping(value = "/cards")
public ResponseEntity<Page<CardsDto>> getCards(Pageable page) {
if (page == null) {
page = getDefaultPageRequest();
}
return new ResponseEntity<>(cardsService.getCards(page), HttpStatus.OK);
}
@GetMapping(value = "/cards/{id}")
public ResponseEntity<CardsDto> getCardsById(@PathVariable("id") Integer id) {
CardsDto Cards = cardsService.getCardsById(id);
return Cards != null
? new ResponseEntity(Cards, HttpStatus.OK)
: new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
public abstract class BaseController {
protected PageRequest getDefaultPageRequest() {
return PageRequest.of(0, 20);
}
}
public interface CardsService {
public void saveCards(CardsDto cardDto);
public Page<CardsDto> customSearch(CardSearch CardSearch, Pageable page);
public Page<CardsDto> getCards(Pageable page);
public CardsDto getCardsById(Integer id);
}
public class CardsServiceImpl extends BaseService<Cards, CardsDto> implements CardsService {
@Autowired
public CardsServiceImpl(CardsRepository cardsRepository) {
super(Cards.class);
this.cardsRepository = cardsRepository;
}
public CardsRepository cardsRepository;
@Override
public void saveCards(CardsDto cardDto) {
save(cardDto);
}
}
public abstract class BaseService<T, R extends BaseDto> {
private JpaRepository<T, Integer> repository;
private final Class< T> clsT;
public BaseService(Class<T> clsT) {
this.clsT = clsT;
}
public Page<R> get(Pageable page, JpaRepository<T, Integer> repository, Function<T, R> convert) {
Page<T> pageR = repository.findAll(page);
List<R> dtos = convertsToDto(pageR.getContent(), convert);
return new PageImpl<>(dtos, page, pageR.getTotalElements());
}
public R getById(Integer id, Function<T, R> convert){
Optional<T> beans = repository.findById(id);
if (beans.isPresent()) {
return convert.apply(beans.get());
}
return null;
}
}
public interface CardsRepository extends JpaRepository<Cards, Integer>, CardsRepositoryCustom {
}
public interface CardsRepositoryCustom {
}
@Repository
public class CardsRepositoryImpl extends SimpleJpaRepository implements CardsRepositoryCustom{
@PersistenceContext
private EntityManager em;
@Autowired
public CardsRepositoryImpl(EntityManager em) {
super(Cards.class, em);
}
....
}
最佳答案
我建议您看看 Spring Data Rest,它可能会帮助您更有效地概括您的代码。
关于java - 使用 spring 创建通用 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45287831/