Это, как я пытаюсь самонастройки Весна в моем Java Web Application:Как я могу сделать объекты доступа WebApplicationContext в ApplicationContext?
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);
}
}
И 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;
}
}
При попытке развертывания приложения Tomcat и запустить I получите:
Вызванный: org.springframework.beans.factory.NoSuchBeanDefinitionException: Нет отборочный боб типа [biz.tugay.janeleven.root.service.AppUserService] найдено для зависимость: ожидается как минимум 1 бит, который квалифицируется как автоузел кандидат на эту зависимость. Зависимость от аннотаций: {@ org.springframework.beans.factory.annotation.Autowired (обязательно = истина)}
Я также включая классы HelloServlet и AppUserService здесь, с их пакета информации:
пакет 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:/";
}
}
Я ожидаю, что, WebContextConfiguration должны быть в состоянии найти бобы, которые управляются RootContextConfiguration, так как я зову:
webContext.setParent(rootContext);
в процессе загрузки. Но, очевидно, я что-то упускаю.
HelloWorldServlet абсолютно не сервлет. Это обработчик Spring MVC. Будьте осторожны с терминологией в коде или вы сбиваете себя с толку. – BalusC