Java 如何避免在webapp中从应用程序上下文检索springbean?
我正在设计一个webapp,我不希望在服务的入口点内调用context.getBean() 理想情况下,我希望@Autowire bean,但是这对我来说不起作用 JUnit测试能够很好地看到自动连线bean,但web应用程序却不能 web.xmlJava 如何避免在webapp中从应用程序上下文检索springbean?,java,spring,spring-mvc,javabeans,autowired,Java,Spring,Spring Mvc,Javabeans,Autowired,我正在设计一个webapp,我不希望在服务的入口点内调用context.getBean() 理想情况下,我希望@Autowire bean,但是这对我来说不起作用 JUnit测试能够很好地看到自动连线bean,但web应用程序却不能 web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring/serviceContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</listener-class>
</listener>
<context:annotation-config/>
<context:component-scan base-package="service.myservice"/>
MyService.class
@WebService(<snipped this out>)
@BindingType("http://schemas.xmlsoap.org/wsdl/soap/http")
public class MyService extends ServiceBase implements ApplicationContextAware {
/** The context. */
@Resource
WebServiceContext context;
@Autowired
ServiceController controller;
public doFeature(...) { return controller.getTimeout();} <----- this is where the NPE is
我不希望每次web请求传入时都必须获取上下文并执行context.getBean()——我希望@Autowire允许我访问该bean
我把Spring放在Debug中,它说bean已经创建了,所以我不确定到底发生了什么
我见过web应用程序使用静态变量来实现这一点,但我不想让任何Bean成为静态的,所以我也试图避免这种情况
你知道我做错了什么吗
决心在阅读了以下JIRA之后,我能够解决它 您的bean是否用@Component注释?谢谢您的建议。我将@Component添加到配置类和服务类中。它已在控制器类上。另一个建议——尽管这可能没什么——是“service.myservicecontroller”(缺少o)的拼写有点奇怪。这是故意的吗?只是当我试图调用它时,对象是空的。我更改了所有项目的名称,因为这是一个工作项目,我不想使用所有项目的真实名称,因为NDAs和所有的爵士乐。:)当我创建一个测试并使用以下内容时,JUnit AssertNotNull()对该对象起作用:@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes=ApplicationConfig.class),因此这取决于web应用程序尝试使用该对象的方式。我真的很想这样设计,我不需要在上下文中调用getBean(),但我似乎无法让它工作。因此,当tomcat服务器启动时,对象就可以了。我可以看到它被初始化没有问题。当web请求传入时,对象为空。
@WebService(<snipped this out>)
@BindingType("http://schemas.xmlsoap.org/wsdl/soap/http")
public class MyService extends ServiceBase implements ApplicationContextAware {
/** The context. */
@Resource
WebServiceContext context;
@Autowired
ServiceController controller;
public doFeature(...) { return controller.getTimeout();} <----- this is where the NPE is
@Component
public class ServiceController {
public int timeout = 100;
public void setTimeout(int t) {
this.timeout = t;
}
public int getTimeout() { return this.timeout; }
public ServiceController(){}
}