我想将 UriInfo
包装到我的自定义查询对象中,并使其在其他 Spring
组件中可用。我能够像这样使用 HK2 做到这一点
package test.service;
@Path("/test")
public class TestResource {
@Inject
private Query query;
@GET
public String test() {
return "found: " + query.toString();
}
}
with proper factory
package test.utils;
public class QueryFactory implements Factory<Query> {
@Inject
private UriInfo uriInfo;
@Override
public Query provide() {
Query query = new Query();
Iterator<String> it = uriInfo.getQueryParameters().keySet().iterator();
if(it.hasNext()) {
String key = it.next();
List<String> valueList = uriInfo.getQueryParameters().get(key);
String value;
if(valueList.isEmpty())
value = "no value";
else
value = valueList.get(0);
query.setKey(key);
query.setValue(value);
} else {
query.setKey("no query");
}
return query;
}
@Override
public void dispose(Query query) {
}
}
Now I would like to switch to spring. I tried by adding configuration
package test.config
@Configuration
@ComponentScan("test")
public class SpringConfiguration {
@Autowired
QueryFactory queryFactory;
@Bean
public Query query() throws Exception {
return queryFactory.getObject();
}
}
updating web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>test.config.SpringConfiguration</param-value>
</context-param>
changing TestResource
package test.service;
@Path("/test")
@Component
public class TestResource {
@Autowired
private Query query;
@GET
public String test() {
return "found: " + query.toString();
}
}
并向 QueryFactory 添加注释
@Component
@Scope("request")
public class QueryFactory implements FactoryBean<Query>
我知道需要 RequestContextListener
才能处理请求范围。但是,当我运行它时,我收到异常告诉我
`java.lang.IllegalStateException: No thread-bound request found:`
您是指实际 Web 请求之外的请求属性,还是在原始接收线程之外处理请求?如果您实际上是在 Web 请求中进行操作并且仍然收到此消息,则您的代码可能在
之外运行DispatcherServlet/DispatcherPortlet:
在这种情况下,使用RequestContextListener或RequestContextFilter来公开当前请求。
这很荒谬,因为我已经将 RequestContextListener 添加到了 web.xml 中。
如果我在未设置 ContextLoaderListener 的情况下运行,则会在 TestResource 中收到 NullPointerException,因为查询为 null。
我看不出哪里出了问题。你能告诉我这个配置应该如何正确完成吗?
最佳答案
问题是你告诉 Spring QueryFactory 有一个请求范围
@Component
@Scope("request")
public class QueryFactory
所以,这个对象只存在于网络请求的中间。但您试图在网络请求之外使用它。
@Autowired
QueryFactory queryFactory;
可以在异常中看到
Are you referring to request attributes outside of an actual web request
关于java - Spring中如何使用request作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34314188/