I'm really new in Spring MVC. I write a demo(use annotation),but it doesn't work. 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[] { "/" };
}
}
in Configure.java,I declare the 'ContackDAO' bean ,like this:
@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();
}
}
in MainControl.java .I need to use ContackDAO,so I write this:
@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";
}
}
when I run this demo, I get errors:
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)}
what's wrong in my demo? Can you help me?
I find if I put the code:
@Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl();
}
into RootConfigure.class
@Configuration
@ComponentScan(basePackages = { "base" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfigure {
@Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl();
}
}
,the demo run successfully.I don't know why...