gpt4 book ai didi

java - 为什么 CDI 不起作用?

转载 作者:行者123 更新时间:2023-12-02 06:33:32 26 4
gpt4 key购买 nike

我有下次休息服务:

@ApplicationPath("geo")
@Path("weather")
public class MainResource extends Application {

@Inject
private MainDep dep;

@GET
public String printGotIt() {
return "Got it!";
}

@GET
@Path("propaganda")
public String printPropaganda() {
return dep.printPropaganda();
}
}

MainDep依赖代码:

public class MainDep {
public String printPropaganda() {
return "Interesting enterprise";
}
}

当我尝试使用以下网址上的资源时:host:port/root/geo/weather GlassFish 抛出 javax.servlet.ServletException:

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
`javax.servlet.ServletException: Servlet.init() for servlet com.app.weather.rs.MainResource threw exception
root cause`
A MultiException has 1 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MainDep,parent=MainResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,22064320)
root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MainDep,parent=MainResource,qualifiers={}),position=-1,optional=false

最佳答案

这里的问题是,您将 JAX-RS 应用程序 + JAX-RS 资源类混合在一个类中,并且最重要的是您将 CDI 注入(inject)添加到混合中。

尝试将 JAX-RS 应用程序与 JAX-RS 资源分开,例如:

@ApplicationPath("geo")
public class MainApplication extends Application {

@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(MainResource.class);
return classes;
}
}

@Path("weather")
public class MainResource {

@Inject
private MainDep dep;

@GET
public String printGotIt() {
return "Got it!";
}

@GET
@Path("propaganda")
public String printPropaganda() {
return dep.printPropaganda();
}
}

关于java - 为什么 CDI 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19876703/

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