我正在使用Spring,在“映射器”的第一个控制器中出现问题:
上下文初始化期间遇到的异常-取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ controller”的bean时出错:通过字段“ mapper”表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.BeanCreationException:创建名称为'modelMapperFactoryBean'的bean时出错:FactoryBean在对象创建时抛出了异常;嵌套的异常是org.modelmapper.ConfigurationException:ModelMapper配置错误:
- 无法实例化的代理实例 实体。确保这件事 实体具有非私有构造函数。
我的实体不是抽象类。在这里:
@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;
}
}
}
答案 0 :(得分:0)
该问题基于不同的Java版本。当它从11降级到8时,一切都很好。