我有两个控制器。
我写了这个控制器,在这里我必须写config才能正确工作。
@Controller
public class BookController {
private BookService bookService;
@Autowired(required = true)
@Qualifier(value = "bookService")
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
@RequestMapping(value = "books", method = RequestMethod.GET)
public String listBooks(Model model){
model.addAttribute("book", new Book());
model.addAttribute("listBooks", this.bookService.listBooks());
return "books";
}
}
@Controller("controller1")
public class AuthorController {
private AuthorService authorService;
@Autowired(required = true)
@Qualifier(value = "authorService")
public void setBookService(AuthorService authorService) {
this.authorService = authorService;
}
@RequestMapping
(value = "authors", method = RequestMethod.GET)
public String listAuthors(Model model){
model.addAttribute("author", new Author());
model.addAttribute("listAuthors", this.authorService.list());
return "";
}
}
答案 0 :(得分:1)
如果您使用基于Xml的配置,请尝试将此配置添加到dispatcherServlet.xml
<context:component-scan base-package="com.example.controllers"/>
,如果您使用基于Java的配置,请将此代码添加到WebMvcConfigurerAdapter实现配置类中
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controllers")
示例:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controllers")
public class SpringConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
答案 1 :(得分:0)
好吧,我相信添加就足够了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
放入pom.xml
并在您的@EnableWebMvc
文件中添加AppConfig
注释
UPD
假设您有一个应用程序com.foo.app.AppName
然后,要解决该问题,您必须创建一个类com.foo.app.AppName.AppConfig
并至少添加以下内容:
@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {
}
实施WebMvcConfigurerAdapter
不是铁腕规则-您可以根据ypu的需要使用任何配置程序
答案 2 :(得分:0)
您可以通过以下方式自动连接服务:
@Controller
@RequestMapping("book")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping("find_all")
public String list(Model model) {
model.addAttribute("book", bookService.findAll());
return "book/list";
}