首页 > > > 关于springmvc.xml文件的问题
为什么在springmvc.xml文件中添加<context:component-scan>标签后,还创建bean失败
下面的Spring mvc代码中,为什么创建bean失败,我已经在springmvc.xml文件中添加<context:component-scan base-package="">了啊
其中,项目目录结构为:

项目报错原因:
Caused by:
org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private com.atguigu.springmvc.UserService com.atguigu.springmvc.HelloWorld.userService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.atguigu.springmvc.UserService] 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)}
下面是文件的具体代码:
其中web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>springmvc.xml文件:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="com.atguigu.springmvc"/> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>HelloWorld.java文件 @Controller public class HelloWorld { @Autowired private UserService userService; public HelloWorld() { System.out.println("HelloWorld Constructor..."); } @RequestMapping("/helloworld") public String hello(){ System.out.println("success"); return "success"; } }
UserService.java
@Service
public class UserService {
@Autowired
private HelloWorld helloWorld;
public UserService() {
System.out.println("UserService Constructor...");
}
}来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4692/viewspace-3168475/ ,如需转载,请注明出处,否则将追究法律责任。