0

我是第一次使用 Spring,尽管我觉得我熟悉核心 IoC 概念,但我无法让 @Autowired 配置正常工作。我创建了这个 github 来演示(堆栈:使用 Jersey/Tomcat/Spring/Maven 的基本服务):

https://github.com/dkwestbr/autowired_example

我没有使用任何类型的 xml 配置(对于 Spring 或 Tomcat)。我可以使用成功启动服务器并映射到我的 Jersey 端点,mvn clean tomcat7:run但我的服务遇到了 NullPointerException,因为我尝试 Autowire 的对象没有被 Spring 框架初始化。

以下是我目前妆容的分解:

为什么弹簧不检测/初始化我的自动装配变量? 我已经阅读了一段时间的教程,并且不知所措。大多数教程都是使用 xml 配置编写的,这无济于事。


以下是我在上面引用的特定代码片段:

我试图通过@Autowired注释初始化变量的类:

@Path("/foo")
public class WebEndpoint {

    @Autowired
    private IStringGetter getTheThing;

    @GET
    @Path("/bar")
    @Produces(MediaType.TEXT_HTML)
    public String getStuff() {
        System.out.println(getTheThing.getItGood());
        return String.format("<html><body>Hello - %s</body></html>", getTheThing.getItGood());
    }
}

我的配置:

@Configuration
@ComponentScan(basePackages = {"dkwestbr.spring.autowired.example.**"})
public class AppConfig {

    @Bean
    private static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Configuration
    @PropertySource("classpath:configuration.properties")
    static class Production { }

    @Configuration
    @Profile("test")
    @PropertySource("classpath:configuration.properties")
    static class Test { }
}

加载配置的位置:

public class Initializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext context) throws ServletException {
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
        appContext.register(AppConfig.class);
        context.addListener(new ContextLoaderListener(appContext));

        Map<String, String> filterParameters = new HashMap<>();

        // set filter parameters
        filterParameters.put("com.sun.jersey.config.property.packages", "dkwestbr.spring.autowired.example");
        filterParameters.put("com.sun.jersey.config.property.JSPTemplatesBasePath", "/WEB-INF/app");
        filterParameters.put("com.sun.jersey.config.property.WebPageContentRegex", "/(images|css|jsp)/.*");

        // register filter
        FilterRegistration.Dynamic filterDispatcher = context.addFilter("webFilter", new ServletContainer());
        filterDispatcher.setInitParameters(filterParameters);
        filterDispatcher.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    }

}

我希望映射到变量的@Configuration/定义:Bean@Autowired

@Component
public class A implements IStringGetter {

    @Bean
    public IStringGetter getTheThing() {
        return new A();
    }

    @Override
    public String getItGood() {
        return "I am an A";
    }

}

更新:我根据要求提供堆栈跟踪(这是第 20 行:System.out.println(getTheThing.getItGood());)....

java.lang.NullPointerException
    dkwestbr.spring.autowired.example.WebEndpoint.getStuff(WebEndpoint.java:20)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
4

2 回答 2

3

快速浏览一下您的课程,在我看来,您似乎没有将 Spring 与 Jersey 集成。将ServletContainer扫描并创建自己的WebEndpoint类实例,但它不知道ServletContext.

如需完整的 Spring-Jersey 集成,请查看本教程。您将需要切换到SpringServlet并添加一个绑定两者的新库。


至于您的配置,注释仅在带注释的类@Bean的上下文中才有意义。@Configuration这没有任何意义

@Component
public class A implements IStringGetter {    
    @Bean
    public IStringGetter getTheThing() {
        return new A();
    }    
    @Override
    public String getItGood() {
        return "I am an A";
    }    
}

摆脱@Bean方法。使用 a @ComponentScan@Component将实例化带注释的类,并将 bean 添加到上下文中。也改变了AppConfig @ComponentScan

@ComponentScan(basePackages = {"dkwestbr.spring.autowired.example"})

它通过那个包重复出现。

您的两个嵌套@Configuration类也没有任何作用。

于 2013-10-10T17:45:45.927 回答
1

对于不是由 Spring 使用管理的 bean extends SpringBeanAutowiringSupport,它应该可以工作。在上面的例子中使类WebEndpoint扩展SpringBeanAutowiringSupport

于 2014-07-12T00:41:02.200 回答