当我的bean被创建时,我一直得到以下错误,但是我不确定为什么它在我声明它时没有看到bean。文件结构有问题还是存在更深层次的问题?我知道这对很多人来说都是TLDR,但我想要包括完整的流程。
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productsController' defined in file [C:\Users\ChappleZ\Desktop\CRCart001\CRCartSpring001\out\artifacts\CRCartSpring001_war_exploded\WEB-INF\classes\cr\controllers\ProductsController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [cr.managers.ProductsManager]: : No matching bean of type [cr.managers.ProductsManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [cr.managers.ProductsManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
以下是文件夹结构和相关文件。
src - Java |_ Cr |_ Controllers |_ ProductsController |_ Dao |_ Impl |_ ProductsDaoImpl |_ ProductsDao |_ Entity |_ Products |_ Managers |_ ProductsManager |_ Impl |_ ProductsManagerImpl - Resources |_ Beans |_ Daos.xml |_ Services.xml |_ Config |_ BeanLocations.xml |_ Database |_ DataSource.xml |_ Hibernate.xml |_ Properties |_ Database.properties Web - Resources |_ Components |_ Css |_ Data |_ Img |_ Js |_ Views - WEB-INF |_ applicationContext.xml |_ dispatcher-servlet.xml |_ logging.properties |_ web.xml - index.jsp
产品控制器
package cr.controllers;
import cr.Entity.Products;
import cr.managers.ProductsManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/Products")
public class ProductsController {
private ProductsManager productsManager;
@Autowired
public ProductsController(ProductsManager productsManager) {
this.productsManager = productsManager;
}
@RequestMapping(
value = "/products/{productId}",
method = RequestMethod.GET)
public
@ResponseBody
Products findByProductId(@PathVariable long productId) {
Products products = productsManager.findByProductId(productId);
return products;
}
}
ProductsDaoImpl
package cr.dao.impl;
import cr.Entity.Products;
import cr.dao.ProductsDao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.util.List;
public class ProductsDaoImpl extends HibernateDaoSupport implements ProductsDao {
@Override
public void save(Products products) {
getHibernateTemplate().save(products);
}
@Override
public void update(Products products) {
getHibernateTemplate().update(products);
}
@Override
public void delete(Products products) {
getHibernateTemplate().delete(products);
}
@Override
public Products findByProductId(Long productId) {
List list = getHibernateTemplate().find("from Products where productId=?",productId);
return (Products)list.get(0);
}
}
用ProductsDao
package cr.dao;
import cr.Entity.Products;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
public interface ProductsDao {
void save(Products products);
void update(Products products);
void delete(Products products);
Products findByProductId(Long productId);
}
ProductsEntity
package cr.Entity;
import com.sun.istack.internal.NotNull;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.persistence.*;
import java.sql.Timestamp;
@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name= "Products")
public class Products {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name= "productsId")
private int productsId;
@Column(name = "ProductName")
@NotNull
private String productName;
@Column(name = "ProductDescription")
@NotNull
private String productDescription;
@Column(name = "MfgCost")
private double mfgCost;
@Column(name = "Price")
private double price;
@Column(name = "SalePrice")
private double salePrice;
@Column(name = "CreationDate")
private Timestamp creationDate;
@Column(name = "DeletedIndicator")
private Boolean deletedIndicator;
@Column(name = "ImagePath")
@NotNull
private String imagePath;
+Setters and Getters + ToString (Not added to keep post shorter)
ProductsManager
package cr.managers;
import cr.Entity.Products;
public interface ProductsManager {
void save(Products products);
void update(Products products);
void delete(Products products);
Products findByProductId(Long productId);
}
ProductsManagerImpl
package cr.managers.impl;
import cr.Entity.Products;
import cr.dao.ProductsDao;
import cr.managers.ProductsManager;
public class ProductsManagerImpl implements ProductsManager{
ProductsDao productsDao;
public void setProductsDao(ProductsDao productsDao){
this.productsDao=productsDao;
}
public void save(Products products) {
productsDao.save(products);
}
public void update(Products products) {
productsDao.update(products);
}
public void delete(Products products) {
productsDao.delete(products);
}
public Products findByProductId(Long productId) {
return productsDao.findByProductId(productId);
}
}
Daos.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Products Data Access Object -->
<bean id="productsDao" class="cr.dao.impl.ProductsDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
的services.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Products object -->
<bean id="productsManager" class="cr.managers.impl.ProductsManagerImpl">
<property name="productsDao" ref="productsDao"/>
</bean>
</beans>
BeanLocations.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Database Configuration -->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- Beans Declaration -->
<import resource="../beans/daos.xml"/>
<import resource="../beans/services.xml"/>
</beans>
DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/database.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
</beans>
Hibernate.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
Database.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/schema
jdbc.username=user
jdbc.password=root
的applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
调度-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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!--================================= Component Scan ======================================-->
<!-- Scans within the base package of the application for @Controller to configure as beans -->
<!-- This entry looks for annotated classes and provides those beans in the Spring container. -->
<!-- So there is no need to declare bean definitions in the XML configuration -->
<context:component-scan base-package="cr"/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:annotation-driven />
<!--SimpleUrlHandlerMapping is already configured, disabling the default HandlerMappings.
The DispatcherServlet enables the DefaultAnnotationHandlerMapping, which looks for @RequestMapping annotations on @Controllers. -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<!-- Based on the value of the order property Spring sorts all handler mappings available in the context and applies the first matching handler. -->
<property name="order" value="1"/>
</bean>
</beans>
logging.properties
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
</web-app>
答案 0 :(得分:2)
建议:
在主应用程序上下文中导入bean定义XML。不要在根上下文中实例化ProductsController - 所有@Controller bean都应该属于MVC servlet上下文。您可以使用MVC xml中的以下标记来实现此目的:
<context:component-scan base-package="cr" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
并在主上下文中将@Component注释添加到您的类中并使用:
<context:component-scan base-package="cr" use-default-filters="true">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
或完全跳过组件扫描并手动定义XML格式的bean
答案 1 :(得分:2)
这是您收到错误的地方:
private ProductsManager productsManager;
@Autowired
public ProductsController(ProductsManager productsManager) {
this.productsManager = productsManager;
}
这不是自动装配bean的正确方法。
用
替换所有内容@Autowired
private ProductsManager productsManager;
您不必为此创建构造函数。或者,您可以在setter上自动装配bean:
private ProductsManager productsManager;
@Autowired
public setProductsManager(ProductsManager productsManager) {
this.productsManager = productsManager;
}
答案 2 :(得分:0)
选项1: -
在web.xml中加载services.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
//Load Services.xml here like <param-value>actualPath/services.xml</param-value>
</context-param>
在service.xml中导入dao.xml
//Like <import resource="classpath:actualClassPath/dao.xml" />
然后
您可以直接在控制器中自动装配productsManager。 您可以直接在productsManager中自动装配productsDao。
由于您自动装配了productsManager,因此控制器中不需要构造函数。 由于您自动连接productsDao,因此productManager中不需要构造函数。
下面的bean配置就足够了。
<bean id="productsManager" class="cr.managers.impl.ProductsManagerImpl"/>
下面的代码足以让控制器使用。
@Controller
@RequestMapping("/Products")
public class ProductsController {
@Autowired
private ProductsManager productsManager;
@RequestMapping(value = "/products/{productId}",
method = RequestMethod.GET)
@ResponseBody
public Products findByProductId(@PathVariable long productId) {
Products products = productsManager.findByProductId(productId);
return products;
}
}
选项2: - (我不建议这样做(这是为了更好地理解))
在applicationContext.xml中定义productsManager,productsDao bean
然后
修改控制器就像上面的代码一样。