gpt4 book ai didi

java - Jersey - 尽管非空初始化,资源变量仍为空值

转载 作者:行者123 更新时间:2023-12-01 20:04:04 26 4
gpt4 key购买 nike

我的 Jersey REST api 中有一个资源,它有一个私有(private)实例变量:

@Path("test")
public class TestResource implements ServletContextListener
{
private String someString;

@GET
public void test()
{
System.out.println("someString " + someString);
}

@Override
public void contextDestroyed(ServletContextEvent ctxt) {
System.out.println("Destroying context");
}

@Override
public void contextInitialized(ServletContextEvent ctxt) {
System.out.println("TestResource initialized!");

someString = "SET";
System.out.println("someString has been set. someString: " + someString);
}
}

在服务器启动/重新启动时,实例变量 someStringcontextInitialized() 期间初始化,并正确打印出来。但是,当我将 GET 请求设置为 http://localhost:8080/myapp/api/test (即调用 test() 方法上面)变量 someStringnull

如何防止这种情况发生?

最佳答案

来自 JAX-RS 规范:

By default a new resource class instance is created for each request to that resource.

因此,您在资源类实例上设置的任何状态都是毫无意义的,因为该实例永远不会再次使用。如果您想保留某个值,请将其放在 ServletContext’s attributes 中:

// All classes in the web app share a ServletContext, so attribute names
// need to start with package names to prevent collisions.
private static final String SOME_ATTRIBUTE = TestResource.class.getName() + ".someAttribute";

@Override
public void contextInitialized(ServletContextEvent ctxt) {
System.out.println("TestResource initialized!");

String someString = "SET";
System.out.println("someString has been set. someString: " + someString);

ctxt.getServletContext().setAttribute(SOME_ATTRIBUTE, someString);
}

@GET
public void test(@Context ServletContext context) {
System.out.println("someString " + context.getAttribute(SOME_ATTRIBUTE));
}

静态字段中存储值将要求您实现线程安全,并且无法在分布式生产环境中工作。

关于java - Jersey - 尽管非空初始化,资源变量仍为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47660029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com