如何在球衣中使用HK2将常量注入某个类?有了Guice,我可以有类似的课程
public class DependsOnFoo {
@Inject
public DependsOnFoo(@Named("FOO") String foo) {
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
我会在注入器中配置类似的东西
bind(String.class).named("FOO").toInstance(new String("foo"))
Run Code Online (Sandbox Code Playgroud)
HK2中的等价物(如果有的话)是多少?
我想初始化Jersey Rest服务并引入一个全局应用程序范围的变量,该变量应该在应用程序启动时计算,并且应该在每个rest资源和每个方法中可用(此处由整数globalAppValue = 17表示,但将是一个复杂的对象后来).
为了初始化服务并在启动时计算一次值,我发现了两种做法:一般的ServletContextListener和Jersey ResourceConfig方法.但是我还没有理解他们俩之间有什么区别?两种方法在启动时触发(两者都打印System.out-messages).
这是我的ServletContextListener的实现,它工作正常:
public class LoadConfigurationListener implements ServletContextListener
{
private int globalAppValue = 17;
@Override
public void contextDestroyed (ServletContextEvent event)
{
}
@Override
public void contextInitialized (ServletContextEvent event)
{
System.out.println ("ServletContext init.");
ServletContext context = event.getServletContext ();
context.setAttribute ("globalAppValue", globalAppValue);
}
}
Run Code Online (Sandbox Code Playgroud)
这是Jersey Rest ResourceConfig方法的实现,其中ServletContext不可用.以后可以通过使用资源方法注入来提供此Application对象:
@ApplicationPath("Resources")
public class MyApplication extends ResourceConfig
{
@Context
ServletContext context;
private int globalAppValue = 17;
public MyApplication () throws NamingException
{
System.out.println ("Application init.");
// returns NullPointerException since ServletContext is not …Run Code Online (Sandbox Code Playgroud)