对于Web应用程序,ApplicationContext为null

时间:2013-04-02 19:08:54

标签: java spring grizzly

我们正在构建一个Web应用程序,在HttpServer启动后,我正在尝试将数据库中的一些项目加载到内存中。我知道如何利用服务层的最佳方法是使用以下类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext (ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}

它一直是空的。

public static void main(String[] args) throws IOException {
    final HttpServer server = HttpServer.createSimpleServer(".", 8181);

    WebappContext ctx = new WebappContext("Socket", "/");

    //enable annotation configuration
    ctx.addContextInitParameter("contextClass", "org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
    ctx.addContextInitParameter("contextLocation", "com.production");

    //allow spring to do all of it's stuff
    ctx.addListener("org.springframework.web.context.ContextLoaderListener");

    //serve static assets
    StaticHttpHandler staticHttpHandler = new StaticHttpHandler("src/main/web");
    server.getServerConfiguration().addHttpHandler(staticHttpHandler, "/");

    //deploy
    ctx.deploy(server);

    //NULL
    WorkflowService workflowService = (WorkflowService) ApplicationContextProvider.getApplicationContext().getBean("workflowService");

    server.start();

服务类使用@Service注释,我的配置类是......

@Configuration
@ComponentScan(basePackages = {
        "com.production"
})
@PropertySource(value= {
        "classpath:/application.properties",
        "classpath:/environment-${MYAPP_ENVIRONMENT}.properties"
})
@EnableJpaRepositories("com.fettergroup.production.repositories")
@EnableTransactionManagement
public class Config {

    ...

    @Bean
    public ApplicationContextProvider applicationContextProvider() {
        return new ApplicationContextProvider();
    }
}

我相信使用灰熊WebContext这个应用程序的一些东西是问题的根源。但我不确定该怎么做。我做了一些谷歌搜索,似乎我正在使用的解决方案应该工作......

1 个答案:

答案 0 :(得分:1)

contextLocation Init参数应为contextConfigLocation