refactor: 重构服务依赖注入和上下文管理

移除硬编码的服务注入,改为使用缓存机制动态获取Bean
优化上下文类结构,统一服务获取方式
添加PageContent类支持分页数据封装
实现异步数据加载功能
This commit is contained in:
2025-09-12 12:20:15 +08:00
parent fc263288e4
commit 422994efcd
16 changed files with 191 additions and 201 deletions

View File

@@ -20,6 +20,7 @@ import org.springframework.data.domain.Sort;
import com.ecep.contract.controller.table.EditableEntityTableTabSkin;
import com.ecep.contract.controller.table.TableTabSkin;
import com.ecep.contract.model.IdentityEntity;
import com.ecep.contract.service.QueryService;
import com.ecep.contract.service.ViewModelService;
import com.ecep.contract.util.TableViewUtils;
import com.ecep.contract.util.UITools;
@@ -419,7 +420,24 @@ public abstract class AbstEntityManagerSkin<T extends IdentityEntity, TV extends
dataSet.clear();
runAsync(() -> {
controller.setStatus("载入中...");
// 异步加载数据
if (getViewModelService() instanceof QueryService<T, TV> queryService) {
asyncLoadTableData(queryService, future);
return;
}
// 同步加载方法
List<TV> models = loadTableData();
_updateModels(models, future);
}).exceptionally(ex -> {
future.completeExceptionally(ex);
return null;
});
});
return future;
}
private void _updateModels(List<TV> models, CompletableFuture<Void> future) {
Platform.runLater(() -> {
try {
updateTableDataSet(models);
@@ -430,12 +448,6 @@ public abstract class AbstEntityManagerSkin<T extends IdentityEntity, TV extends
future.completeExceptionally(e);
}
});
}).exceptionally(ex -> {
future.completeExceptionally(ex);
return null;
});
});
return future;
}
/**
@@ -489,6 +501,25 @@ public abstract class AbstEntityManagerSkin<T extends IdentityEntity, TV extends
return page.map(service::from).toList();
}
/**
* 异步加载表格数据
*
* @param queryService
* @param future
*/
private void asyncLoadTableData(QueryService<T, TV> queryService, CompletableFuture<Void> future) {
queryService.asyncFindAll(getSpecification(), getPageable()).whenComplete((result, ex) -> {
if (ex != null) {
future.completeExceptionally(ex);
return;
}
updateFooter(result);
List<TV> models = result.map(getViewModelService()::from).toList();
_updateModels(models, future);
});
}
/**
* 获取ViewModelService
*

View File

@@ -51,18 +51,6 @@ public class CloudTycManagerSkin
return companyService;
}
@Override
protected List<CloudTycInfoViewModel> loadTableData() {
String searchText = controller.searchKeyField.getText();
Map<String, Object> spec = new HashMap<>();
if (StringUtils.hasText(searchText)) {
spec.put("searchText", searchText);
}
Page<CloudTyc> page = getCloudTycService().findAll(spec, getPageable());
updateFooter(page);
return page.map(CloudTycInfoViewModel::from).toList();
}
@Override
public void initializeTable() {
controller.idColumn.setCellValueFactory(param -> param.getValue().getId());

View File

@@ -41,18 +41,6 @@ public class YongYouU8ManagerSkin
return getBean(CompanyService.class);
}
@Override
protected List<CloudYuInfoViewModel> loadTableData() {
String searchText = controller.searchKeyField.getText();
Map<String, Object> params = ParamUtils.builder().build();
if (StringUtils.hasText(searchText)) {
params.put("searchText", searchText);
}
Page<CloudYu> page = getU8Service().findAll(params, getPageable());
updateFooter(page);
return page.map(CloudYuInfoViewModel::from).toList();
}
@Override
public void initializeTable() {
controller.idColumn.setCellValueFactory(param -> param.getValue().getId());

View File

@@ -64,22 +64,7 @@ public class ContractManagerSkin
public Map<String, Object> getSpecification() {
Map<String, Object> params = super.getSpecification();
if (controller.composeViewBtn.isSelected()) {
// TODO 完善查询条件
params.put("payWay", ContractPayWay.RECEIVE);
// spec = SpecificationUtils.and(spec, (root, query, builder) -> {
// Path<String> parentCode = root.get("parentCode");
// Path<ContractPayWay> payWay = root.get("payWay");
// return builder.or(
// builder.equal(payWay, ContractPayWay.RECEIVE),
// builder.and(
// builder.equal(payWay, ContractPayWay.PAY),
// builder.or(
// builder.equal(parentCode, ""),
// parentCode.isNull())));
// });
}
ContractGroup selectedGroup = controller.groupSelector.getValue();
if (selectedGroup != null) {

View File

@@ -9,11 +9,10 @@ import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import com.ecep.contract.PageArgument;
import com.ecep.contract.PageContent;
import com.ecep.contract.WebSocketService;
import com.ecep.contract.model.IdentityEntity;
import com.ecep.contract.msg.SimpleMessage;
@@ -103,7 +102,6 @@ public class QueryService<T extends IdentityEntity, TV extends IdentityViewModel
return null;
}
if (response == null) {
return null;
}
T newEntity = createNewEntity();
@@ -130,17 +128,23 @@ public class QueryService<T extends IdentityEntity, TV extends IdentityViewModel
return findAll(null, Pageable.unpaged()).getContent();
}
@Override
public Page<T> findAll(Map<String, Object> params, Pageable pageable) {
public CompletableFuture<Page<T>> asyncFindAll(Map<String, Object> params, Pageable pageable) {
SimpleMessage msg = new SimpleMessage();
msg.setService(getBeanName());
msg.setMethod("findAll");
msg.setArguments(params, PageArgument.of(pageable));
try {
JsonNode response = webSocketService.send(msg).get(readTimeout, TimeUnit.MILLISECONDS);
if (response != null) {
return webSocketService.send(msg).orTimeout(readTimeout, TimeUnit.MILLISECONDS).handle((response, ex) -> {
if (ex != null) {
return null;
}
if (response == null) {
return null;
}
PageContent<T> pageContent = new PageContent<>();
try {
List<T> content = new ArrayList<>();
if (response.has("content")) {
JsonNode contentNode = response.get("content");
if (contentNode != null && contentNode.isArray()) {
for (JsonNode node : contentNode) {
@@ -149,19 +153,34 @@ public class QueryService<T extends IdentityEntity, TV extends IdentityViewModel
content.add(newEntity);
}
}
}
pageContent.setContent(content);
if (response.has("page")) {
JsonNode pageNode = response.get("page");
int total = pageNode.get("totalElements").asInt();
int totalPages = pageNode.get("totalPages").asInt();
int size = pageNode.get("size").asInt();
int number = pageNode.get("number").asInt();
PageRequest newPageable = PageRequest.of(number, size);
return new PageImpl<>(content, newPageable, total);
PageArgument pageArgument = objectMapper.treeToValue(pageNode, PageArgument.class);
pageContent.setPage(pageArgument);
}
if (response.has("totalElements")) {
int totalElements = response.get("totalElements").asInt();
pageContent.setTotalElements(totalElements);
}
if (response.has("totalPages")) {
int totalPages = response.get("totalPages").asInt();
pageContent.setTotalPages(totalPages);
}
} catch (Exception e) {
throw new RuntimeException(e);
throw new RuntimeException(response.toString(), e);
}
return pageContent.toPage();
});
}
@Override
public Page<T> findAll(Map<String, Object> params, Pageable pageable) {
try {
return asyncFindAll(params, pageable).get();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

View File

@@ -10,11 +10,15 @@ import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.NullHandling;
import org.springframework.data.domain.Sort.Order;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class PageArgument {
private boolean paged = false;
@@ -54,6 +58,7 @@ public class PageArgument {
return Pageable.unpaged(sort);
}
@JsonIgnore
public boolean isUnpaged() {
return !isPaged();
}

View File

@@ -0,0 +1,32 @@
package com.ecep.contract;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import lombok.Data;
@Data
public class PageContent<T> {
private List<T> content;
private PageArgument page;
private int totalElements;
private int totalPages;
public static <T> PageContent<T> of(Page<T> page) {
PageContent<T> content = new PageContent<>();
content.setContent(page.getContent());
content.setPage(PageArgument.of(page.getPageable()));
content.setTotalElements((int) page.getTotalElements());
content.setTotalPages(page.getTotalPages());
return content;
}
public Page<T> toPage() {
PageImpl<T> page = new PageImpl<>(content == null ? List.of() : content, getPage().toPageable(), totalElements);
return page;
}
}

View File

@@ -1,21 +1,25 @@
package com.ecep.contract.cloud;
import static com.ecep.contract.SpringApp.getBean;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.springframework.beans.BeansException;
import org.springframework.util.StringUtils;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.other.service.SysConfService;
import com.ecep.contract.util.MyStringUtils;
import com.ecep.contract.util.NumberUtils;
@@ -24,18 +28,35 @@ import lombok.Getter;
import lombok.Setter;
public class AbstractCtx {
@Setter
SysConfService confService;
@Setter
@Getter
Locale locale = Locale.getDefault();
private Map<Class<?>, Object> cachedBeans = new HashMap<>();
public <T> T getBean(Class<T> requiredType) throws BeansException {
return SpringApp.getBean(requiredType);
}
@SuppressWarnings("unchecked")
public <T> T getCachedBean(Class<T> requiredType) throws BeansException {
Object object = cachedBeans.get(requiredType);
if (object == null) {
object = getBean(requiredType);
cachedBeans.put(requiredType, object);
}
return (T) object;
}
public SysConfService getConfService() {
if (confService == null) {
confService = getBean(SysConfService.class);
return getCachedBean(SysConfService.class);
}
return confService;
public CompanyService getCompanyService() {
return getCachedBean(CompanyService.class);
}
public EmployeeService getEmployeeService() {
return getCachedBean(EmployeeService.class);
}
public boolean updateText(Supplier<String> getter, Consumer<String> setter, String text, MessageHolder holder,

View File

@@ -205,10 +205,6 @@ public class YongYouU8Service implements IEntityService<CloudYu>, QueryService<C
public void initialize(AbstractYongYouU8Ctx ctx) {
ctx.setRepository(repository);
ctx.setCompanyService(companyService);
ctx.setEmployeeService(employeeService);
ctx.setCompanyVendorService(companyVendorService);
ctx.setCompanyCustomerService(companyCustomerService);
}
public Iterable<CloudInfo> findAllCloudYu() {

View File

@@ -1,7 +1,5 @@
package com.ecep.contract.cloud.u8.ctx;
import static com.ecep.contract.SpringApp.getBean;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
@@ -17,7 +15,6 @@ import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.customer.service.CompanyCustomerEntityService;
import com.ecep.contract.ds.customer.service.CompanyCustomerService;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.vendor.service.CompanyVendorEntityService;
import com.ecep.contract.ds.vendor.service.CompanyVendorService;
import com.ecep.contract.model.Company;
@@ -34,26 +31,9 @@ public class AbstractYongYouU8Ctx extends AbstractCtx {
@Getter
@Setter
YongYouU8Repository repository;
@Setter
CompanyService companyService;
@Setter
EmployeeService employeeService;
@Setter
CompanyCustomerService companyCustomerService;
@Setter
CompanyCustomerEntityService companyCustomerEntityService;
@Setter
CompanyVendorService companyVendorService;
@Setter
CompanyVendorEntityService companyVendorEntityService;
public void from(AbstractYongYouU8Ctx parent) {
repository = parent.repository;
companyService = parent.companyService;
employeeService = parent.employeeService;
companyCustomerService = parent.companyCustomerService;
companyVendorService = parent.companyVendorService;
}
public void initializeRepository(MessageHolder holder) {
@@ -67,50 +47,28 @@ public class AbstractYongYouU8Ctx extends AbstractCtx {
}
}
public CompanyService getCompanyService() {
if (companyService == null) {
companyService = getBean(CompanyService.class);
}
return companyService;
}
EmployeeService getEmployeeService() {
if (employeeService == null) {
employeeService = getBean(EmployeeService.class);
}
return employeeService;
return getCachedBean(CompanyService.class);
}
public CompanyCustomerService getCompanyCustomerService() {
if (companyCustomerService == null) {
companyCustomerService = getBean(CompanyCustomerService.class);
}
return companyCustomerService;
return getCachedBean(CompanyCustomerService.class);
}
public CompanyCustomerEntityService getCompanyCustomerEntityService() {
if (companyCustomerEntityService == null) {
companyCustomerEntityService = getBean(CompanyCustomerEntityService.class);
}
return companyCustomerEntityService;
return getCachedBean(CompanyCustomerEntityService.class);
}
public CompanyVendorService getCompanyVendorService() {
if (companyVendorService == null) {
companyVendorService = getBean(CompanyVendorService.class);
}
return companyVendorService;
return getCachedBean(CompanyVendorService.class);
}
public CompanyVendorEntityService getCompanyVendorEntityService() {
if (companyVendorEntityService == null) {
companyVendorEntityService = getBean(CompanyVendorEntityService.class);
}
return companyVendorEntityService;
return getCachedBean(CompanyVendorEntityService.class);
}
boolean updateEmployeeByCode(Supplier<Employee> getter, Consumer<Employee> setter, String code, MessageHolder holder, String topic) {
boolean updateEmployeeByCode(Supplier<Employee> getter, Consumer<Employee> setter, String code,
MessageHolder holder, String topic) {
if (StringUtils.hasText(code)) {
Employee employee = getEmployeeService().findByCode(code);
if (employee != null) {
@@ -124,8 +82,8 @@ public class AbstractYongYouU8Ctx extends AbstractCtx {
return false;
}
boolean updateEmployeeByName(Supplier<Employee> getter, Consumer<Employee> setter, String name, MessageHolder holder, String topic) {
boolean updateEmployeeByName(Supplier<Employee> getter, Consumer<Employee> setter, String name,
MessageHolder holder, String topic) {
if (StringUtils.hasText(name)) {
Employee employee = getEmployeeService().findByName(name);
if (employee != null) {
@@ -139,7 +97,8 @@ public class AbstractYongYouU8Ctx extends AbstractCtx {
return false;
}
boolean updateCompanyByCustomerCode(Supplier<Company> getter, Consumer<Company> setter, String customerCode, MessageHolder holder, String topic) {
boolean updateCompanyByCustomerCode(Supplier<Company> getter, Consumer<Company> setter, String customerCode,
MessageHolder holder, String topic) {
Company company = null;
if (StringUtils.hasText(customerCode)) {
CompanyCustomerEntityService customerEntityService = getCompanyCustomerEntityService();
@@ -176,8 +135,8 @@ public class AbstractYongYouU8Ctx extends AbstractCtx {
return false;
}
boolean updateCompanyByVendorCode(Supplier<Company> getter, Consumer<Company> setter, String vendorCode, MessageHolder holder, String topic) {
boolean updateCompanyByVendorCode(Supplier<Company> getter, Consumer<Company> setter, String vendorCode,
MessageHolder holder, String topic) {
Company company = null;
if (StringUtils.hasText(vendorCode)) {
CompanyVendorEntityService vendorEntityService = getCompanyVendorEntityService();
@@ -214,5 +173,4 @@ public class AbstractYongYouU8Ctx extends AbstractCtx {
return false;
}
}

View File

@@ -1,7 +1,5 @@
package com.ecep.contract.cloud.u8.ctx;
import static com.ecep.contract.SpringApp.getBean;
import java.io.File;
import java.text.NumberFormat;
import java.time.LocalDate;
@@ -30,6 +28,7 @@ import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.ds.company.CompanyFileUtils;
import com.ecep.contract.ds.contract.service.ContractFileService;
import com.ecep.contract.ds.contract.service.ContractFileTypeService;
import com.ecep.contract.ds.contract.service.ContractItemService;
import com.ecep.contract.ds.contract.service.ContractPayPlanService;
import com.ecep.contract.ds.contract.service.ContractService;
@@ -66,16 +65,6 @@ import lombok.Setter;
* 合同上下文
*/
public class ContractCtx extends AbstractYongYouU8Ctx {
@Setter
private ContractService contractService;
@Setter
private ContractItemService contractItemService;
@Setter
private ContractFileService contractFileService;
@Setter
private ContractPayPlanService contractPayPlanService;
@Setter
private SaleTypeService saleTypeService;
@Setter
private VendorCtx vendorCtx;
@Setter
@@ -92,38 +81,25 @@ public class ContractCtx extends AbstractYongYouU8Ctx {
@Getter
@Setter
private int customerEntityUpdateDelayDays = 1;
public ContractService getContractService() {
if (contractService == null) {
contractService = getBean(ContractService.class);
}
return contractService;
}
ContractItemService getContractItemService() {
if (contractItemService == null) {
contractItemService = getBean(ContractItemService.class);
}
return contractItemService;
return getCachedBean(ContractService.class);
}
ContractPayPlanService getContractPayPlanService() {
if (contractPayPlanService == null) {
contractPayPlanService = getBean(ContractPayPlanService.class);
}
return contractPayPlanService;
public ContractItemService getContractItemService() {
return getCachedBean(ContractItemService.class);
}
ContractFileService getContractFileService() {
if (contractFileService == null) {
contractFileService = getBean(ContractFileService.class);
}
return contractFileService;
public ContractPayPlanService getContractPayPlanService() {
return getCachedBean(ContractPayPlanService.class);
}
SaleTypeService getSaleTypeService() {
if (saleTypeService == null) {
saleTypeService = getBean(SaleTypeService.class);
public ContractFileService getContractFileService() {
return getCachedBean(ContractFileService.class);
}
return saleTypeService;
public SaleTypeService getSaleTypeService() {
return getCachedBean(SaleTypeService.class);
}
VendorCtx getVendorCtx() {
@@ -1223,8 +1199,8 @@ public class ContractCtx extends AbstractYongYouU8Ctx {
MyDateTimeUtils.pickLocalDate(file.getName()), holder, "生效日期");
}
List<ContractFileTypeLocal> matched = getContractFileService()
.findAllFileTypes(Locale.getDefault().toLanguageTag()).values().stream()
List<ContractFileTypeLocal> matched = getCachedBean(ContractFileTypeService.class)
.findAll(getLocale()).values().stream()
.filter(local -> {
if (payWay == ContractPayWay.PAY) {
return local.getType().isSupportVendor();

View File

@@ -137,7 +137,7 @@ public class ContractService implements IEntityService<Contract>, QueryService<C
}
// field
spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "parentCode");
spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "payWay", "parentCode");
// relation
spec = SpecificationUtils.andParam(spec, paramsNode, "group", "kind", "type", "group", "company", "project");

View File

@@ -77,10 +77,6 @@ public abstract class AbstContractRepairTasker extends Tasker<Object> {
return purchaseBillVoucherCtx;
}
public void setContractService(ContractService contractService) {
contractCtx.setContractService(contractService);
}
@Override
protected Object execute(MessageHolder holder) throws Exception {
try {

View File

@@ -31,7 +31,6 @@ public class ContractFilesRebuildAllTasker extends Tasker<Object> {
ContractCtx getContractCtx() {
if (contractCtx == null) {
contractCtx = new ContractCtx();
contractCtx.setContractService(getContractService());
}
return contractCtx;
}

View File

@@ -1,14 +1,11 @@
package com.ecep.contract.ds.project;
import static com.ecep.contract.SpringApp.getBean;
import java.util.Objects;
import org.hibernate.Hibernate;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.cloud.AbstractCtx;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.project.service.ProjectService;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.Project;
@@ -18,8 +15,7 @@ import lombok.Setter;
public class ProjectCtx extends AbstractCtx {
@Setter
private ProjectService projectService;
@Setter
CompanyService companyService;
ProjectService getProjectService() {
if (projectService == null) {
@@ -28,13 +24,6 @@ public class ProjectCtx extends AbstractCtx {
return projectService;
}
CompanyService getCompanyService() {
if (companyService == null) {
companyService = getBean(CompanyService.class);
}
return companyService;
}
public boolean updateCustomer(Project project, Company customer, MessageHolder holder) {
boolean modified = false;
if (!Objects.equals(project.getCustomer(), customer)) {

View File

@@ -16,6 +16,8 @@ import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
@@ -27,6 +29,7 @@ import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.ecep.contract.IEntityService;
import com.ecep.contract.PageArgument;
import com.ecep.contract.PageContent;
import com.ecep.contract.QueryService;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.other.service.EmployeeLoginHistoryService;
@@ -48,6 +51,8 @@ import lombok.Data;
@Component
public class WebSocketHandler extends TextWebSocketHandler {
private final AuthenticationManager authenticationManager;
private final ObjectMapper objectMapper;
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
@@ -78,8 +83,9 @@ public class WebSocketHandler extends TextWebSocketHandler {
}
}
WebSocketHandler(ObjectMapper objectMapper) {
WebSocketHandler(ObjectMapper objectMapper, AuthenticationManager authenticationManager) {
this.objectMapper = objectMapper;
this.authenticationManager = authenticationManager;
}
/**
@@ -317,7 +323,8 @@ public class WebSocketHandler extends TextWebSocketHandler {
JsonNode pageableNode = argumentsNode.get(1);
PageArgument pageArgument = objectMapper.treeToValue(pageableNode, PageArgument.class);
QueryService<?> entityService = (QueryService<?>) service;
return entityService.findAll(paramsNode, pageArgument.toPageable());
Page<?> page = entityService.findAll(paramsNode, pageArgument.toPageable());
return PageContent.of(page);
}
private void sendError(WebSocketSession session, String messageId, String message) {