我有一个web应用程序,它有一个UserService,允许与用户相关的操作。
我可以在我的任何一个UserService类中自动配置@Controller bean,它可以正常工作。
如果我添加第二个ThriftServlet类型的servlet,如下所示:
//register the thrift API servlet
ServletRegistration.Dynamic thrift = servletContext.addServlet("thriftapi", new ThriftServlet());
thrift.setLoadOnStartup(2);
thrift.addMapping("/api/*");ThriftServlet看起来是这样的:
public class ThriftServlet extends TServlet {
// constructor
public ThriftServlet() {
super(new MyService.Processor<ThriftApiHandler>(
new ThriftApiHandler()), new TBinaryProtocol.Factory());
}
}然后,我用@Component装饰我的@Component,以便允许注入bean (或者我认为是这样的),这样看起来如下:
@Component
public class ThriftApiHandler implements MyService.Iface {
@Autowired
UserService userService;
@Override
public String myServiceMethod(String someParam) throws SomeException, TException {
// userService is null when this is called by a client application
}
}在调试日志中,我可以看到自动装配确实正在进行(时间戳和类片段):
<snip> - Creating shared instance of singleton bean 'thriftApiHandler'
<snip> - Creating instance of bean 'thriftApiHandler'
<snip> - Registered injected element on class [my.package.api.ThriftApiHandler]: AutowiredFieldElement for my.package.service.UserService my.package.api.ThriftApiHandler.userService
<snip> - Eagerly caching bean 'thriftApiHandler' to allow for resolving potential circular references
<snip> - Processing injected method of bean 'thriftApiHandler': AutowiredFieldElement for my.package.service.UserService my.package.api.ThriftApiHandler.userService但是userService (以及我尝试注入的任何其他bean)在任何一个节俭api方法中都是空的。
也许这与TServlet类如何从HttpServlet继承权利而不“了解”spring上下文有关吗?
我觉得自己缺少了与servlet上下文和共享bean等相关的东西,但我对SpringMVC非常陌生。如果发布更多的代码会使这个问题更容易回答,请告诉我。
发布于 2013-12-05 15:53:32
如果Spring不能解析@Autowired目标,它总是会失败(抛出异常)。如果您得到了null,那么Spring实际上并不管理您的对象,因此不能注入任何东西。这里的情况就是这样。
public ThriftServlet() {
super(new MyService.Processor<ThriftApiHandler>(
new ThriftApiHandler()), new TBinaryProtocol.Factory()); // here
}您正在实例化您的ThriftApiHandler,而不是从Spring获取它。
如果您想从Spring获得它,您将需要从ApplicationContext属性或放置它的任何地方访问它。
发布于 2013-12-05 17:20:58
我终于明白了.
@Component添加到ThriftServlet类ThriftProcessor的新类(参见下面),它也是一个@ComponentThriftServlet构造函数(见下文)更改为@Autowired并接受Processor参数ThriftServlet,而不是自己实例化它(注意:必须告诉ApplicationContext刷新自己才能工作)ThriftProcessor类:
@Component
public class ThriftProcessor extends MyService.Processor<ThriftApiHandler> {
@Autowired
public ThriftProcessor(ThriftApiHandler iface) {
super(iface);
}
}ThriftServlet类:
@Component
public class ThriftServlet extends TServlet {
@Autowired
public ThriftServlet(Processor<ThriftApiHandler> p) {
super(p, new TBinaryProtocol.Factory());
}
}初始化器中的新servlet配置:
//register the thrift API servlet using a spring bean
ServletRegistration.Dynamic thrift = servletContext.addServlet("thriftapi", (ThriftServlet) ctx.getBean("thriftServlet")); // get thriftServlet from springbeans!
thrift.setLoadOnStartup(2);
thrift.addMapping("/api/*");如果有一种“更好”的方法,请说出来!
https://stackoverflow.com/questions/20404468
复制相似问题