【发布时间】:2016-05-06 05:13:05
【问题描述】:
我是 Spring MVC 的新手。我写了一个演示(使用注释),但它不起作用。 here is the construction of my demo
public class WebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfigure.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { Configure.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
在 Configure.java 中,我声明了 'ContackDAO' bean,如下所示:
@Configuration
@ComponentScan(basePackages = "base")
@EnableWebMvc
public class Configure extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/");
}
@Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl();
}
}
在 MainControl.java 中。我需要使用 ContackDAO,所以我写了这个:
@Controller
public class MainControl {
@Autowired
private ContactDAO contactDAO;
@RequestMapping(value="/")
public String listContact() throws IOException{
System.out.println(contactDAO.getBean());// getBean() returns "hello"
return "hello";
}
}
当我运行这个演示时,我得到了错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainControl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private base.dao.ContactDAO base.contorl.MainControl.contactDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [base.dao.ContactDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我的演示有什么问题?你能帮帮我吗?
如果我把代码我发现:
@Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl();
}
进入 RootConfigure.class
@Configuration
@ComponentScan(basePackages = { "base" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfigure {
@Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl();
}
}
,demo运行成功,不知道为什么...
【问题讨论】:
-
你有多少个配置类?
标签: java spring spring-mvc