我正在尝试启动Web应用程序,但是存在BeanCreationException,它表示未建立自动装配的依赖项。
错误是这样的: 例外 javax.servlet.ServletException:Servlet [mvc-dispatcher]的Servlet.init()抛出异常 org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:853) org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1587) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.base / java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) java.base / java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:628) org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61) java.base / java.lang.Thread.run(Thread.java:834)
根本原因
org.springframework.beans.factory.BeanCreationException:创建名称为'coffeeController'的bean时出错:自动连接依赖项的注入失败;嵌套的异常是org.springframework.beans.factory.BeanCreationException:无法自动装配方法:public void app.controller.CoffeeController.setCoffeeService(app.service.CoffeeService);嵌套的异常是org.springframework.beans.factory.BeanCreationException:使用ServletContext资源[/WEB-INF/mvc-dispatcher-servlet.xml]中定义的名称为'coffeeService'的bean创建错误:设置时无法解析对bean'coffeeDao'的引用bean属性“ coffeeDao”;嵌套的异常是org.springframework.beans.factory.BeanCreationException:创建在ServletContext资源[/WEB-INF/mvc-dispatcher-servlet.xml]中定义的名称为'coffeeDao'的bean时出错:bean的实例化失败;嵌套异常是java.lang.NoClassDefFoundError:无法初始化类app.dao.CoffeeDaoImpl org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:304) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:853) org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1587) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.base / java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) java.base / java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:628) org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61) java.base / java.lang.Thread.run(Thread.java:834)
控制器类示例。
public class CoffeeController {
private CoffeeService coffeeService;
@Autowired(required = true)
@Qualifier(value = "coffeeService")
public void setCoffeeService(CoffeeService coffeeService) {
this.coffeeService = coffeeService;
}
@RequestMapping(value = "coffees", method = RequestMethod.GET)
public String listCoffee(Model model) {
model.addAttribute("coffee", new Coffee());
model.addAttribute("listCoffee", this.coffeeService.listCoffee());
return "coffees";
}
@RequestMapping(value = "/coffees/add", method = RequestMethod.POST)
public String addCoffee(@ModelAttribute("coffee") Coffee coffee) {
if (coffee.getId() == 0) {
this.coffeeService.addCoffee(coffee);
} else {
this.coffeeService.updateCoffee(coffee);
}
return "redirect:/coffees";
}
@RequestMapping("/remove/{id}")
public String removeCoffee(@PathVariable("id") int id) {
this.coffeeService.removeCoffee(id);
return "redirect:/coffees";
}
@RequestMapping("edit/{id}")
public String editCoffee(@PathVariable("id") int id, Model model) {
model.addAttribute("coffee", this.coffeeService.getCoffeeById(id));
model.addAttribute("listCoffees", this.coffeeService.listCoffee());
return "coffees";
}
@RequestMapping("coffeedata/{id}")
public String coffeeData(@PathVariable("id") int id, Model model) {
model.addAttribute("coffee", this.coffeeService.getCoffeeById(id));
return "coffeedata";
}
}
web.xml
<?xml version="1.0"?>
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">
<display-name>Coffee Shop</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
mvc-dispatcher-servlet-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:tx="http://www.springframework.org/schema/tx"
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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="app"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.postgres.jdbc.Driver"/>
<property name="url"
value="jdbc:postgresql://localhost:5432/postgres"/>
<property name="username" value="postgres"/>
<property name="password" value="postgres"/>
</bean>
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>app.model.Coffee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="coffeeDao" class="app.dao.CoffeeDaoImpl">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<bean id="coffeeService" class="app.service.CoffeeServiceImpl">
<property name="coffeeDao" ref="coffeeDao"/>
</bean>
<context:component-scan base-package="app"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springapp</groupId>
<artifactId>CoffeeShop</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>CoffeeShop</name>
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<hibernate.version>4.3.5.Final</hibernate.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<!--PostgreSQL-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<finalName>BookManger</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</project>
CoffeeDaolmpl
package app.dao;
import app.model.Coffee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.logging.Logger;
@Repository
public class CoffeeDaoImpl implements CoffeeDao {
private static final Logger logger = (Logger) LoggerFactory.getLogger(CoffeeDaoImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void addCoffee(Coffee coffee) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(coffee);
logger.info("Кофе " + coffee + " успешно добавлен");
}
@Override
public void updateCoffee(Coffee coffee) {
Session session = this.sessionFactory.getCurrentSession();
session.update(coffee);
logger.info("Кофе " + coffee + " был успешно изменен");
}
@Override
public void removeCoffee(int id) {
Session session = this.sessionFactory.getCurrentSession();
Coffee coffee = (Coffee) session.load(Coffee.class, id);
if (coffee != null) {
session.delete(coffee);
}
logger.info("Кофе " + coffee + " успешно удален.");
}
@Override
public Coffee getCoffeeById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Coffee coffee = (Coffee) session.load(Coffee.class, id);
logger.info("Выбранный кофе: " + coffee);
return coffee;
}
@Override
@SuppressWarnings("unchecked")
public List<Coffee> listCoffee() {
Session session = this.sessionFactory.getCurrentSession();
List<Coffee> coffeeList = session.createQuery("from Coffee").list();
for (Coffee coffee : coffeeList) {
logger.info("Coffee list " + coffee);
}
return coffeeList;
}
}