简体   繁体   English

如何在ApplicationContext中使WebApplicationContext访问bean?

[英]How can I make WebApplicationContext access beans in ApplicationContext?

This is how I try to bootstrap Spring in my Java Web Application: 这是我尝试在Java Web应用程序中引导Spring的方法:

public class SpringBootstrap implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        final AnnotationConfigApplicationContext rootContext = new AnnotationConfigApplicationContext();
        rootContext.register(RootContextConfiguration.class);

        final AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.register(WebContextConfiguration.class);
        webContext.setParent(rootContext);

        final DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
        final ServletRegistration.Dynamic dispatcher = servletContext.addServlet("springDispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        final ContextLoaderListener contextLoadListener = new ContextLoaderListener(webContext);
        servletContext.addListener(contextLoadListener);
    }
}

And RootContextConfiguration and WebContextConfiguration classes are as follows: RootContextConfiguration和WebContextConfiguration类如下:

@Configuration
@ComponentScan(basePackages = "biz.tugay.janeleven.root")
public class RootContextConfiguration {
}

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "biz.tugay.janeleven.web")
public class WebContextConfiguration {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        return resolver;
    }
}

When I try deploying the application to Tomcat and start I will get: 当我尝试将应用程序部署到Tomcat并启动时,我将得到:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [biz.tugay.janeleven.root.service.AppUserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 由以下原因引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到依赖类型为[biz.tugay.janeleven.root.service.AppUserService]的合格Bean:预计至少有1个有资格作为该依赖项的自动装配候选的bean。 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 依赖项注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

I am also including the HelloServlet and AppUserService classes here, with their package information: 我还将在此处包括HelloServlet和AppUserService类及其包信息:

package biz.tugay.janeleven.root.service; 软件包biz.tugay.janeleven.root.service;

@Service
public class AppUserService {

    public AppUser addAppUser(String name) {
        final AppUser appUser = new AppUser(name);
        AppUserDB.addUser(appUser);
        return appUser;
    }

    public Collection<AppUser> getAllAppUsers() {
        return AppUserDB.getAll();
    }
}

package biz.tugay.janeleven.web;

@Controller
@RequestMapping(value = "/")
public class HelloWorldServlet {

    @Autowired
    private AppUserService appUserService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String helloWorld(Model model) {
        final Collection<AppUser> appUserList = appUserService.getAllAppUsers();
        model.addAttribute("appUserList", appUserList);
        return "hello.jsp";
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public String addApplicationUser(@RequestParam("username") String username) {
        appUserService.addAppUser(username);
        return "redirect:/";
    }

}

My expectation is that, WebContextConfiguration should be able to find beans that are managed by RootContextConfiguration since I am calling: 我的期望是,自从我打电话时,WebContextConfiguration应该能够找到由RootContextConfiguration管理的bean。

webContext.setParent(rootContext);

during the bootstrap process. 在引导过程中。 But obviously I am missing something. 但是显然我缺少了一些东西。

You are correct that the web context will inherit from the root context, however you did not include the rootContext when you initialized servletContext.addListener(); 您是正确的,Web上下文将继承自根上下文,但是初始化ServletContext.addListener()时未包括rootContext。 see similar code below which will help you fix your issue. 请在下面查看类似的代码,这将帮助您解决问题。

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(AppConfig.class);
    servletContext.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(WebConfig.class);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 春季:通过ApplicationContext访问主bean - Spring: access primary beans via ApplicationContext Spring WebApplicationContext 继承了beans? - Spring WebApplicationContext inherits beans? 如何通过ApplicationContext访问属性 - How do I access a property via the ApplicationContext 之间的关联: SpringIocContainer | 应用上下文 | 网络应用上下文 - Associatation between : SpringIocContainer | ApplicationContext | WebApplicationContext 春季:WebApplicationContext和ApplicationContext之间的链接? - Spring: link between WebApplicationContext and ApplicationContext? 如何从服务层中的applicationContext.xml访问bean。 - How to access beans from the applicationContext.xml in my service layer. 如何在抽象类方法中访问注入的 Grails bean? - How can I access injected Grails beans in an abstract class method? 如何将加载在applicationContext中的spring bean转换为接口? - How to cast spring beans loaded in applicationContext to interface? 如何在无参数构造函数中访问Spring bean? - How can I access Spring beans in no-arg constructor? SpringCore-我可以使用@ContextConfiguration在主类中加载bean,而不是创建ApplicationContext obj来加载bean吗? - SpringCore - Can I use @ContextConfiguration to load beans in main class instead of creating ApplicationContext obj to load bean?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM