当前位置: 首页 > 知识库问答 >
问题:

确保实体具有非私有构造函数

丁阎宝
2023-03-14

我正在使用Spring并在“mapper”字段的第一个控制器中遇到问题:

上下文初始化期间遇到异常-取消刷新尝试:org。springframework。豆。工厂UnsatisfiedPendencyException:创建名为“controller”的bean时出错:未满足的依赖项通过字段“mapper”表示;嵌套的异常是org。springframework。豆。工厂BeanCreationException:创建名为“modelMapperFactoryBean”的bean时出错:FactoryBean在创建对象时引发异常;嵌套的异常是org。模型映射器。ConfigurationException:ModelMapper配置错误:

  1. 实例化实体的代理实例失败。确保实体具有非私有构造函数。

我的实体不是抽象类。这里是:

@Entity
@Table(name = "entity", schema = "public")
public class Entity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @JsonIgnoreProperties("agency")
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "entity_id", foreignKey = @ForeignKey(name = "entity_fk", value = ConstraintMode.CONSTRAINT))
    private Agency agency;

    @Column(name = "brand_name", nullable = false, length = 255)
    private String brandName;

    @Column(name = "brand_image")
    private String brandImage;

    @Column(name = "billing_contact")
    @Email(message = "This field should be valid email")
    private String billingContact;

    public Entity() {}

看起来还行。我的控制器不能初始化:

@RestController
@RequestMapping("/")
@PreAuthorize("hasAnyRole('ROLE_AGENT')")
public class Controller extends BaseController {
    @Autowired
    private ModelMapper mapper;

    @Autowired
    private Service service;

    logic...

我有用于映射的配置:

    @Component
    public class ModelMapperCustomConfigurer extends ModelMapperCustomConfigurerBase {
    
        private static final String DATE_FORMAT = "yyyy-MM-dd";
    
        public void configure(ModelMapper modelMapper) {
            super.configure(modelMapper);
            modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    
            TypeMap<Entity, EntityDTO> entityEntityDTOTypeMap = modelMapper.createTypeMap(Entity.class, EntityDTO.class);
            entityEntityDTOTypeMap.addMapping(Entity::getBrandImage, EntityDTO::setBrandLogo);

..other mapping not of Entity...

我发现它是关于抽象实体的,但我没有抽象,我犯了这个错误...为什么啊?

UPD

public class BaseController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AgentRepository agentRepository;

    @Autowired
    private CampaignRepository campaignRepository;

    @Autowired
    private ManagementRepository managementRepository;

    @Autowired
    private JWTVerifier jwtVerifier;

    @Autowired
    private HttpServletRequest request;

    private static final String AGENT_GROUP_NAME = "agents";
    private static final String INTERNAL_GROUP_NAME = "internal";

    Logger logger = LoggerFactory.getLogger(BaseController.class);
    
    protected void jwtVerify() {
        String jwtToken = request.getHeader(Jwt.JWT_HEADER_NAME);
        
        if (jwtToken == null) {
            throw new UnauthorizedException(String.format("Header '%s' not found", Jwt.JWT_HEADER_NAME));
        }
        
        String backdoor = request.getHeader("thisisyuri");
        if (backdoor != null && backdoor.equals("1")) {
            return;
        }

        try {
            jwtVerifier.verify(jwtToken);
        } catch (JWTVerificationException e) {
            throw new UnauthorizedException(e.getMessage());
        }
    }

    /**
     * Return the logged in user's token or thorws an exception if no token is found
     *
     * @return
     */
    protected TokenData getTokenData() {
        Object tokenObj = request.getAttribute(JwtInterceptor.TOKEN_HEADER_NAME);
        if (tokenObj == null) {
            throw new UnauthorizedException("No token provided");
        }
        
        // token verify
        jwtVerify();
        
        return (TokenData) tokenObj;
    }

    /**
     * Gets the logged in user or throws exception if it is not found
     *
     * @return
     */
    protected IGenericUser getUserByToken() {
        TokenData token = getTokenData();
        if (isAgent(token)) {
            Agent existingAgent = agentRepository.findByUid(token.sub)
                    .orElseThrow(() -> {
                        String msg = String.format("Agent not found for Uid: %s", token.sub);
                        logger.warn(msg);
                        return new ResourceNotFoundException(msg);
                    });

            /* For internal admin use - pretend to be a different user */
            if (isInternal(token)) {
                /* Check if pretendUID is set/reset */
                final String switchedUid = request.getHeader("pretendUID");
                if (switchedUid != null) {
                    User pretendUser = null;
                    if (switchedUid.equals("0")) {
                        existingAgent.setPretendUid(null);
                    } else {
                        /* Supporting only pretend to be an influencer for now */
                        pretendUser = userRepository.findByUid(switchedUid)
                                .orElseThrow(() -> {
                                    String msg = String.format("Pretend User not found for Uid: %s", switchedUid);
                                    logger.warn(msg);
                                    return new ResourceNotFoundException(msg);
                                });
                        existingAgent.setPretendUid(pretendUser.getUid());
                    }
                    agentRepository.save(existingAgent);
                    if (pretendUser != null) {
                        return pretendUser;
                    }
                } else {
                    /* Check if pretendUID already present */
                    final String pretendUid = existingAgent.getPretendUid();
                    if (pretendUid != null) {
                        return userRepository.findByUid(pretendUid)
                                .orElseThrow(() -> {
                                    String msg = String.format("Pretend User not found for Uid: %s", pretendUid);
                                    logger.warn(msg);
                                    return new ResourceNotFoundException(msg);
                                });
                    }
                }

            }

            return existingAgent;
        }
        Optional<User> existingUser = userRepository.findByUid(token.sub);
        return existingUser.orElseThrow(() -> new ResourceNotFoundException("User not found"));
    }

    /**
     * Checks if the user is part of the agent group
     * 
     * @param token
     * @return
     */
    protected boolean isAgent(TokenData token) {
        return token.groups != null && (token.groups.contains(AGENT.getCognitoName()) ||
                token.groups.contains(BRAND_OWNER.getCognitoName()) ||
                token.groups.contains(SUPER_ADMIN.getCognitoName()) ||
                token.groups.contains(VIEWER.getCognitoName()) ||
                token.groups.contains(AGENT_GROUP_NAME)); // TODO remove AGENT_GROUP_NAME with removing "agents" Cognito group
    }

    /**
     * Checks if the user is part of both the agent group and the internal group - for cross-agency access
     *
     * @param token
     * @return
     */
    protected boolean isInternal(TokenData token) {
        return this.isAgent(token) && token.groups.contains(INTERNAL_GROUP_NAME);
    }

    /**
     * Gets the logged in user and checks if he is authorized based class given. If the user is of different type it is also considered unauthorized
     * 
     * @param id
     * @param clazz
     * @return
     */
    protected <T extends IGenericUser> T checkAndGetUserAuthorized(Long id, Class<T> clazz) {
        T loggedInUser = checkAndGetUserAuthorized(clazz);
        if (!loggedInUser.getId().equals(id)) {
            throw new UnauthorizedException();
        }
        return loggedInUser;
    }

    /**
     * Overload of {@link BaseController#checkAndGetUserAuthorized(Long, Class)} to accept uid instead of id
     * 
     * @param uid
     * @param clazz
     * @return
     */
    protected <T extends IGenericUser> T checkAndGetUserAuthorized(String uid, Class<T> clazz) {
        T loggedInUser = checkAndGetUserAuthorized(clazz);
        if (!loggedInUser.getUid().equals(uid)) {
            throw new UnauthorizedException();
        }
        return loggedInUser;
    }

    /**
     * Gets the logged in user and checks if he is authorized based on the id and class given. If the user has a different id than the value provided throws
     * {@link UnauthorizedException}. If the user is of different type it is also considered unauthorized
     * 
     * @param clazz
     * @return
     */
    protected <T extends IGenericUser> T checkAndGetUserAuthorized(Class<T> clazz) {
        IGenericUser loggedInUser = getUserByToken();
        if (!clazz.isInstance(loggedInUser)) {
            throw new UnauthorizedException();
        }

        return (T) loggedInUser;
    }

    /**
     * Gets the logged in agent and checks if he has permission on the given campaignId. THe permission is checked based on the agency of the agent and the
     * given campaign
     */
    protected Agent checkAndGetAgentAuthorized(long campaignId) {
        IGenericUser loggedInUser = getUserByToken();
        if (!(loggedInUser instanceof Agent)) {
            throw new UnauthorizedException();
        }

        Agent agent = (Agent) loggedInUser;
        Campaign campaign = campaignRepository.findById(campaignId).orElseThrow(() -> new ResourceNotFoundException("Campaign not found for id " + campaignId));
        if (!doesUserHaveRole(SUPER_ADMIN) && agent.getAgentBrandRoles().stream().noneMatch(role -> role.getAgencyBrand().equals(campaign.getAgencyBrand()))) {
            throw new UnauthorizedException();
        }

        return agent;
    }

    protected boolean doesUserHaveRole(RoleType roleType) {
        return request.isUserInRole(roleType.getSecurityName());
    }

    protected User verifyTMPermissionsAndGetSpecifiedInfluencer(User tm, TalentManagerPermission tmPermission, String infUidParam) {
        /* Check if an influencer Uid specified using infUidParam */
        String infUid = request.getParameter(infUidParam);
        if ((infUid == null) || (infUid.length() == 0)) {
            throw new BadRequestException(String.format("[%s] request param is needed when posting as the Talent Manager", infUidParam));
        }

        /* Check if specified influencer Uid is valid */
        User influencer = userRepository.findByUidAndType(infUid, UserType.INFLUENCER)
                .orElseThrow(() -> new ResourceNotFoundException("Influencer", "uid", infUid));

        /* check if this TM can post on behalf of specified influencer */
        Management management = managementRepository.findByInfluencerAndTalentManager(influencer, tm);
        if (management == null) {
            throw new IllegalArgumentException(String.format("Influencer with uid %s not connected to current talent manager", infUid));
        } else if (!management.getManagementPermissionsSet().permits(tmPermission)) {
            throw new IllegalArgumentException(String.format("Insufficient privileges to carryout task on behalf of influencer %s", infUid));
        } else {
            return influencer;
        }
    }

}

共有1个答案

马嘉勋
2023-03-14

这个问题基于不同的Java版本。当它从11降到8时,一切都很好。

 类似资料:
  • 问题内容: 在春季,bean的类可能没有公共构造函数,而只有私有构造函数吗?创建bean时会调用此私有构造函数吗?谢谢。 问题答案: 是的,Spring可以调用私有构造函数。如果找到具有正确参数的构造函数,无论可见性如何,它将使用反射将其构造函数设置为可访问的。

  • 我正在研究一个springboot应用程序,它公开了一些不返回原始实体的endpoint,但它们返回了它们的DTO。为了映射所有的实体,我使用version:2.3.8和project Lombok来避免实现getters、setters和其他一些实用程序。 这些是源实体(我删除了一些属性和Hibernate注释,因为它们在示例中不是必需的): user.java Player.java Coac

  • 问题内容: 为什么将只有私有构造函数的类标记为final是一个好习惯?我的猜测是,要让其他程序员知道它不能被子类化。 问题答案: 将类定为final具有一些(小的)性能提升,因为JIT编译器可以内联该类的功能。我不知道这是否符合“良好做法”的要求,但是我看到了好处。

  • 我试图理解为什么在谈到构造函数时,类成员的可访问性之间存在差异。 考虑下面的例子: 的私有成员作为私有成员,不应从访问。对于字段和方法,情况确实如此,但构造函数似乎没有遵循相同的规则。 从JLS-8(6.6.1.确定可访问性)中,我们可以阅读: [...] 引用类型的成员(类、接口、字段或方法)或类类型的构造函数只有在类型可访问且声明该成员或构造函数允许访问时才可访问: > [……] 否则,成员或

  • 我有一个java类,它只有静态方法和字段,所以我不想为此创建任何对象。我可以从两个方面来理解, 创建类摘要 使用私有构造函数。 这两种方法哪一种更好?

  • 问题内容: 由于枚举构造函数只能由其常量调用,因此为什么要允许它成为包私有的? 问题答案: 构造函数实际上不是包私有的…隐式地意味着接口方法是隐式的,即使您不添加关键字也是如此。 JLS(第8.8.3节)的相关部分规定: 如果没有为普通类的构造函数指定访问修饰符,则该构造函数具有默认访问权限。 如果没有为枚举类型的构造函数指定访问修饰符,则构造函数为。 如果枚举类型(第8.9节)的构造函数声明为或