简体   繁体   中英

How to avoid retrieving spring beans from application context in webapp?

I'm designing a webapp and I would prefer not to have to call context.getBean() inside my entry point to the service.

Ideally I would like to @Autowire beans, however this is not working for me.

The JUnit tests are able to see the Autowired beans just fine, but the web application is not.

web.xml

<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>

serviceContext.xml

<context:annotation-config/>
<context:component-scan base-package="service.myservice"/>

ApplicationConfiguration.java

@Configuration
@ComponentScan(basePackages={"service.myservicecontrller"})
public class ApplicationConfiguration {

    @Autowired ServiceController controller;
}

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

ServiceController.java

@Component
public class ServiceController {
public int timeout = 100;
public void setTimeout(int t) {
this.timeout = t;
}
public int getTimeout() { return this.timeout; }
public ServiceController(){}
}

I don't want to have to get the context and do context.getBean() every time a web request comes in - I was hoping the @Autowire would allow me to access the bean.

I put Spring in Debug and it says the bean is created, so I am not sure what is going on.

I've seen web apps do this using static variables but I don't want to make any of the beans static, so I'm trying to avoid that as well.

Any ideas what I am doing wrong?

RESOLVED! After reading the following JIRA I was able to resolve it. https://jira.spring.io/browse/SPR-9786

您的bean是否带有@Component注释?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM