我正在创建一个 Spring Boot 应用程序,其中包含产品、类别、机械、使用位置等实体。所有这些实体的共同点是它们都有一个名为 name 的 String 属性,并且可以使用 name 从 UI 中过滤。我已经编写了一个使用名称进行过滤的产品规范,并且它正在工作。下面是代码
public final class ProductSpecifications
{
public static Specification<Product> whereNameContains(String name)
{
Specification<Product> finalSpec = (Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder cb)
-> cb.like(root.get(Product_.PRODUCT_NAME), "%"+name+"%");
return finalSpec;
}
public static Specification<Product> whereNameEqauls(String name)
{
Specification<Product> finalSpec = (Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder cb)
-> cb.equal(root.get(Product_.PRODUCT_NAME), name);
return finalSpec;
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是我必须再次编写相同的代码来过滤其他实体,唯一的区别是类名(Product)、字段名称(Product_NAME)和方法的返回类型。我可以创建一个通用类和方法吗?我可以将类名和字段名作为参数传递给它,并返回相应返回类型的规范。
我正在创建一个以 Zuul 作为网关的微服务架构项目。我在名为 common-service 的服务中处理了所有身份验证。我已经公开了一个来自公共服务的 API 来返回当前登录的用户。这工作正常。
现在,我有另一个微服务,称为库存。在库存的服务类中,我想在多种方法中使用当前登录的用户名。因此,我正在对公共服务进行网络客户端调用并获取当前用户名。这工作正常,但每次我需要用户名时,我都会对公共服务进行网络客户端 API 调用。示例 - 如果我添加一个新条目,执行 API 调用,然后再次更新 API 调用等。这似乎不是一种优化的方式
所以问题是 - 我想在全局级别进行此 API 调用。即,每当我的服务 bean 被自动装配时,就应该进行这个 API 调用,并且用户名应该存储在我可以在服务调用中跨方法使用的地方。
我尝试了 @PostConstruct 和 @SessionAttributes 但无法解决确切的问题。
有人可以帮助我提供最适合的解决方案或概念来处理这个问题。
下面是代码片段
public class LeadService
{
@Autowired
WebClient.Builder webClientBuilder;
@Autowired
UserDetailsService userDetailsService;
//more autowiring
private void setLeadFields(Lead lead, @Valid LeadCreateData payload,String type)
{
//some logic
if(type.equalsIgnoreCase("create"))
{
lead.setAsigneeId(userDetailsService.getCurrentUser().getId());
lead.setCreatorId(userDetailsService.getCurrentUser().getId());
}
else if(type.equalsIgnoreCase("update"))
{
//some logic
}
}
private StatusEnum setLeadStatus(Lead lead, StatusEnum status,String string)
{
LeadStatus lstatus=null;
switch(string)
{
case …Run Code Online (Sandbox Code Playgroud)