Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Jhipster-JpaRepository“principal.username”@Query-org.springframework.expression.spel.SpelEvaluationException_Java_Testing_Spring Security_Jhipster_Spelevaluationexception - Fatal编程技术网

Java Jhipster-JpaRepository“principal.username”@Query-org.springframework.expression.spel.SpelEvaluationException

Java Jhipster-JpaRepository“principal.username”@Query-org.springframework.expression.spel.SpelEvaluationException,java,testing,spring-security,jhipster,spelevaluationexception,Java,Testing,Spring Security,Jhipster,Spelevaluationexception,在特定方法上测试rest控制器时出错。我正在使用@Query注释进行数据库查询。它使用principal.username来完成。我不知道principal.username是如何在我的应用程序中获取和使用的。我目前正在查看有关它的spring安全文档。但我的问题是在测试部分,当我执行下面的测试时,由于@Query,我有一个错误Faillure 存储库: public interface MeetingRepository extends JpaRepository<Meeting,Lon

在特定方法上测试rest控制器时出错。我正在使用@Query注释进行数据库查询。它使用principal.username来完成。我不知道principal.username是如何在我的应用程序中获取和使用的。我目前正在查看有关它的spring安全文档。但我的问题是在测试部分,当我执行下面的测试时,由于@Query,我有一个错误Faillure

存储库:

public interface MeetingRepository extends JpaRepository<Meeting,Long> {

  @Query("select m from Meeting m where m.visibility = 'PUBLIC' OR m.user.login = ?#{principal.username}")
  List<Meeting> findOpenAndUserMeetings();

}
这个错误是:

getAllMeetings(com.ent.web.rest.MeetingResourceTest)  Time elapsed: 0.07 sec  <<< ERROR!
    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 10): Property or field 'username' cannot be found on object of type 'java.lang.String' - maybe not public?
        at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:226)
        at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:93)
        at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:46)
        at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:372)
        at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
        at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:131)
        at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:299)
        at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.evaluateExpression(SpelExpressionStringQueryParameterBinder.java:131)
        at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.potentiallyBindExpressionParameters(SpelExpressionStringQueryParameterBinder.java:89)
        at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:69)
        at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateCountQuery(AbstractStringBasedJpaQuery.java:109)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createCountQuery(AbstractJpaQuery.java:190)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:173)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:97)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:88)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:395)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:373)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        at com.sun.proxy.$Proxy148.findOpenAndUserMeetings(Unknown Source)
        at com.ent.web.rest.MeetingResource.getAll(MeetingResource.java:77)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
        at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
        at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
        at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
        at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144)
        at com.ent.web.rest.MeetingResourceTest.getAllMeetings(MeetingResourceTest.java:151)
然后,您可以在查询中引用Spring Security的主体。例如:

public interface BlogRepository extends JpaRepository<Blog,Long> {
    @Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
    List<Blog> findAllForCurrentUser();
}

这是一个上下文问题吗

在我的项目中,我有一个在查询中使用{principal.username}的存储库。下面是它的样子:

public interface BlogRepository extends JpaRepository<Blog, Long> {

    @Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
    List<Blog> findAllForCurrentUser();
}
为了测试这一点,我升级到Spring Security 4.0.1,并添加了对Spring Security test的依赖:

<spring-security.version>4.0.1.RELEASE</spring-security.version>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>${spring-security.version}</version>
    <scope>test</scope>
</dependency>
然后,我修改了getAllBlogs测试,以使用SpringSecurity的WithUserUserUserUserName功能

 @Test
 @Transactional
 public void getAllBlogs() throws Exception {
    restBlogMockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();

     // Initialize the database
     blog.setUser(userRepository.findOneByLogin("user").get());
     blogRepository.saveAndFlush(blog);

     // Get all the blogs
    restBlogMockMvc.perform(get("/api/blogs").with(user("user")))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.[*].id").value(hasItem(blog.getId().intValue())))
        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
        .andExpect(jsonPath("$.[*].handle").value(hasItem(DEFAULT_HANDLE.toString())));
 }
我不知道为什么Spring Security的测试注释@WithMockUser和@WithUserDetails不起作用。一周前我问了一个问题:


谢谢你的回答。它正在工作,希望@WithMockUser和@WithUserDetails会有办法。我知道现在是2017年,但这在jhipster 5.8.2中仍然存在吗?我很容易就找到了解决这个问题的方法。我在回答中没有要点。public static void CreateUserInContextWith authorities with PringUserDetailString主体、字符串凭据、集合权限{User springUserDetail=新用户主体、凭据、权限;SecurityContext SecurityContext=SecurityContextHolder.createEmptyContext;SecurityContext.setAuthenticationnew UsernamePasswordAuthenticationTokenspringUserDetail、凭据、权限;SecurityContextHolder.setContextsecurityContext;
public interface BlogRepository extends JpaRepository<Blog, Long> {

    @Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
    List<Blog> findAllForCurrentUser();
}
 @Timed
 public List<Blog> getAll() {
     log.debug("REST request to get all Blogs for current user");
     return blogRepository.findAllForCurrentUser();
 }
<spring-security.version>4.0.1.RELEASE</spring-security.version>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>${spring-security.version}</version>
    <scope>test</scope>
</dependency>
@Autowired
WebApplicationContext context;

@Inject
UserRepository userRepository;
 @Test
 @Transactional
 public void getAllBlogs() throws Exception {
    restBlogMockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();

     // Initialize the database
     blog.setUser(userRepository.findOneByLogin("user").get());
     blogRepository.saveAndFlush(blog);

     // Get all the blogs
    restBlogMockMvc.perform(get("/api/blogs").with(user("user")))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.[*].id").value(hasItem(blog.getId().intValue())))
        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
        .andExpect(jsonPath("$.[*].handle").value(hasItem(DEFAULT_HANDLE.toString())));
 }