java - Web 应用程序的 ApplicationContext 为 null

标签 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();
    }
}

我相信这个使用 grizzly WebContext 的应用程序的某些内容是问题的根源。但我不确定该怎么办。我已经做了一些谷歌搜索,看来我正在使用的解决方案应该有效......

最佳答案

contextLocation 初始化参数应为 contextConfigLocation

关于java - Web 应用程序的 ApplicationContext 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15772328/

相关文章:

java - 按单选按钮两次,计算两次

java - LWJGL - 加载声音和字体而不平滑

java - 方法参数的@Pattern注解

unix - JerseyTest Grizzly Web 服务器在 Unix 上的行为

jersey - 如何在灰熊上使用 jersey 2.0 guice

java - 加载太多 JPEG 文件(100 秒)导致内存不足错误

java - Spring MVC 中的 Controller 和 Handler 有什么区别?

java - Spring boot 中实体的使用与 Dto 的使用

mysql - 在 Spring boot 中使用 .sql 文件中的初始数据填充 MySql DB

java.lang.NoSuchMethodError : org. glassfish.jersey.server.ApplicationHandler.<初始化>