如何将上下文/ bean配置添加到JAXRSServerFactoryBean

时间:2018-10-09 03:43:48

标签: java spring rest cxf

我在春季嵌入了cxf, 但是,我的cxf REST服务无法自动连接DAO。请帮忙!

cxf REST服务由以下触发:

JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(CustomerService.class);
sf.setAddress("http://localhost:9000/");
sf.create();

serviceImpl.java

@Autowired 
SomeDAO someDAO; 

public void getSomething() {
    someDAO.get(); // get NullPointerException
}

Appconfig.java

@Bean
someBean someBean(){
  return new someBeanImpl();
}

我认为问题在于 Appconfig.java 上下文没有被JAXRSServerFactoryBean注册。那我怎么添加呢?

1 个答案:

答案 0 :(得分:0)

我已解决此问题,只需在此处发布我的解决方案即可帮助其他人。

不要使用“ setResourceClasses(CustomerService.class);”当您使用Spring模仿的cxf时!!!如果以这种方式使用资源类,那么将在Spring上下文之外创建服务bean。因此,请按照以下步骤启动服务器:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(config.class);
ctx.refresh()

JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(ctx.getBean(CustomerService.class));    
// use service interafce if you have both implementation class and interface
// but make sure don't create/new a service class
// which is actually created out of your spring context
// therefore in that service, the @Autowired is not working

sf.setAddress("http://localhost:9000/");
sf.create();

希望这对其他人有帮助!