내 스프링 부트 애플리케이션은 컨트롤러에서 두 서비스에 액세스해야 할 때까지 꽤 잘 작동했습니다. CreateCompany 메소드에서 회사를 db에 저장하기 전에 사용자가 존재하는지 확인하고 싶습니다. 회사 데이터는 adminId 경로 변수와 마찬가지로 올바르게 수신됩니다.
이것은 한 번 작동하지만 동일한 사용자에 대해 다른 회사를 삽입하려는 경우 사용자를 조회하려고 할 때 ClassCastException이 발생합니다.
하지만 이상한 점은 다른 클래스에서 CompanyTagService를 사용하여 데이터베이스에 태그를 성공적으로 삽입한다는 것입니다. 디버깅시 CompanyTagService 개체로 표시되고 CompanyService 및 UserService는 프록시입니다. 이것은 나에게 의심 스럽지만 유용한 것을 알아내는 스프링 프록시에 대해서는 거의 알지 못합니다.
내가 도대체 뭘 잘못하고있는 겁니까?
CompanyServiceBean.java
@RestController
@RequestMapping( value="/api/company")
public class CompanyController {
@Value( "${application.config.logo_folder}" )
private String logoFolder;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private CompanyService service;
@Autowired
private CompanyTagService tagService;
@Autowired
private UserService uService;
@RequestMapping(
value="/admin/{adminId}",
method=RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE )
public ResponseEntity< ? > CreateCompany( @RequestBody Company company, @PathVariable( "adminId") Long adminId ){
Company ret = null;
ResponseEntity< ? > resp = null;
User u = uService.findOne( adminId ); //This is where the exception occurrs.
if( null != u )
logger.info( "User {} was found.", u.getFirstName() );
logger.info( "Creating company record for admin with id {}", adminId);
if( u == null ){
resp = new ResponseEntity< RestResult >( new RestResult( "The user id must be set", HttpStatus.BAD_REQUEST ), HttpStatus.BAD_REQUEST );
}
else {
company.setAdminId(adminId);
try{
ret = service.create( company );
resp = new ResponseEntity< Company >( ret, HttpStatus.CREATED );
}
catch( DataIntegrityViolationException ie ){
resp = new ResponseEntity< RestResult >( new RestResult( "Company name or org. no. was already in use", HttpStatus.BAD_REQUEST ), HttpStatus.BAD_REQUEST);
}
catch( Exception e ){
resp = new ResponseEntity< RestResult >( new RestResult( "Could not create the company.", HttpStatus.INTERNAL_SERVER_ERROR ), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return( resp );
}
... Other service methods
UserServiceBean.java :
@Service
@Transactional( propagation = Propagation.SUPPORTS, readOnly = true )
public class UserServiceBean implements UserService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserRepository userRepo;
@Override
@CachePut( value="EntWeb", key="#result.id" )
@Transactional( propagation = Propagation.REQUIRED, readOnly = false )
public User create(User user) {
User ret = null;
if( user.getId() == null ) {
ret = userRepo.save( user );
}
return( ret );
}
@Override
@Cacheable( value="EntWeb", key="#id")
public User findOne(Long id) {
User ret = userRepo.findOne( id );
return( ret );
}
... Other Service methods
오류 출력
java.lang.ClassCastException: org.entweb.model.Company cannot be cast to org.entweb.model.User
at com.sun.proxy.$Proxy126.findOne(Unknown Source) ~[na:na]
at org.entweb.web.api.CompanyController.CreateCompany(CompanyController.java:58) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_77]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_77]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_77]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_77]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817) ~[spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731) ~[spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
내 마음에 유일한 문제는 캐시입니다. 즉, 다른 개체를 하나의 캐시에 넣습니다. 피터는 그것이 문제임을 확인했습니다.
이를 수정하려면 ... 두 가지 방법이 있습니다.
이를 수행하려면 cachePut 사양을 참조하십시오. Values 속성은 업데이트해야하는 캐시를 알려주는 데 사용하는 속성이며이 특정 결과 개체를 포함합니다. 대부분의 프로젝트에서 사용하는 접두사를 점 - EntWeb.users.admins
- 또는 어쩌면 entweb.users
충분하다. 아름다움은 나중에 변경할 수 있다는 것입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다