gpt4 book ai didi

java - 确保 Entity 有一个非私有(private)的构造函数

转载 作者:行者123 更新时间:2023-12-05 05:01:14 24 4
gpt4 key购买 nike

我正在使用 Spring 并在“映射器”字段的第一个 Controller 中遇到问题:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controller': Unsatisfied dependency expressed through field 'mapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'modelMapperFactoryBean': FactoryBean threw exception on object creation; nested exception is org.modelmapper.ConfigurationException: ModelMapper configuration errors:

  1. Failed to instantiate proxied instance ofEntity. Ensure thatEntity has a non-private constructor.

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

@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() {}

看起来还可以。我的 Controller 无法初始化:

@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;
}
}

}

最佳答案

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

关于java - 确保 Entity 有一个非私有(private)的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62792542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com