简体   繁体   中英

Error creating bean with name 'homeController': Injection of autowired dependencies failed

I am trying to create e-commerce in spring. After including "Hibernate" and "H2" database in my project, I get the error. The error is given below. I am trying very much but not found any solution.

Error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.home.dao.ProductDao com.home.controller.homeController.productDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.home.dao.impl.ProductDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution

applicationContext.xml

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:~/test" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">true</prop>
        </props>
    </property>
    <property name="packagesToScan">
        <list>
            <value>com.home</value>
        </list>
    </property>
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean> 

home-servlet.xml

<context:component-scan base-package="com.home">
    <context:include-filter type="aspectj" expression="com.home.*" />
</context:component-scan>

<mvc:annotation-driven />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>

</bean>

<mvc:resources mapping="/resources/**"
    location="/WEB-INF/resources/" cache-period="31556926" />


<tx:annotation-driven />

web.xml

<display-name>Archetype Created Web Application</display-name>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/home-servlet.xml,
        /WEB-INF/applicationContext.xml
    </param-value>
</context-param>

<servlet>
    <servlet-name>home</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>home</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

homeController.java

@Controller
@Configuration
public class homeController {

@Autowired
private ProductDao productDao;

@RequestMapping("/")
public String home() {
    return "views/home";
}


@RequestMapping("/productList")
public String getProducts(Model model) {
    List<Product> products = productDao.getAllProducts();
    model.addAttribute("products", products);

    return "views/productList";
}

@RequestMapping("/productList/viewProduct/{productId}")
public String viewProduct(@PathVariable String productId, Model model) throws IOException{

    Product product = productDao.getProductById(productId);
    model.addAttribute(product);

    return "views/viewProduct";
}

}

ProductDaoImpl.java

@Repository
@Transactional
public class ProductDaoImpl implements ProductDao {

@Autowired
private SessionFactory sessionFactory;

public void addProduct(Product product) {
    Session session = sessionFactory.getCurrentSession();
    session.saveOrUpdate(product);
    session.flush();
}

public Product getProductById(String id) {
    Session session = sessionFactory.getCurrentSession();
    Product product = (Product) session.get(Product.class, id);
    session.flush();

    return product;
}

public List<Product> getAllProducts() {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from Product");
    List<Product> products = query.list();
    session.flush();

    return products;
}

public void deleteProduct (String id) {
    Session session = sessionFactory.getCurrentSession();
    session.delete(getProductById(id));
    session.flush();
}

}

Product.java Code:

@Entity

public class Product {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
private String productName;
private String productCategory;
private String productDescription;
private double productPrice;
private String productCondition;
private String productStatus;
private int unitInStock;
private String productManufacturer;

public String getProductId() {
    return productId;
}

public void setProductId(String productId) {
    this.productId = productId;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public String getProductCategory() {
    return productCategory;
}

public void setProductCategory(String productCategory) {
    this.productCategory = productCategory;
}

public String getProductDescription() {
    return productDescription;
}

public void setProductDescription(String productDescription) {
    this.productDescription = productDescription;
}

public double getProductPrice() {
    return productPrice;
}

public void setProductPrice(double productPrice) {
    this.productPrice = productPrice;
}

public String getProductCondition() {
    return productCondition;
}

public void setProductCondition(String productCondition) {
    this.productCondition = productCondition;
}

public String getProductStatus() {
    return productStatus;
}

public void setProductStatus(String productStatus) {
    this.productStatus = productStatus;
}

public int getUnitInStock() {
    return unitInStock;
}

public void setUnitInStock(int unitInStock) {
    this.unitInStock = unitInStock;
}

public String getProductManufacturer() {
    return productManufacturer;
}

public void setProductManufacturer(String productManufacturer) {
    this.productManufacturer = productManufacturer;
}

}

ProductDao.java Code: public interface ProductDao {

void addProduct(Product product);

Product getProductById(String id);

List<Product> getAllProducts();

void deleteProduct(String id);

}

Project Structure or Directory Image: Project Structure or Directory at my Eclipse Oxygen IDE

ProductDao is not a bean..That's why. Repository, controller, service are all of type of bean. Make sure this is which type of bean.....Thank you.

Finally, I have found my own problems when I use IntelliJ IDEA IDE. Problems are given bellow:

  1. My problem have occurred at pom.xml file. Here, I have used hibernate-core latest version ( 5.4.0.Final ) dependency which is not support import org.hibernate.Query; package and also not support Query query = session.createQuery("from Product"); and Product product = (Product) session.get(Product.class, id); codes at ProductDaoImpl.java class.

  2. I have also used latest version of spring-webmvc , spring-core and spring-orm dependency at pom.xml file. For that it occurs version conflict.

Solution:

  1. Forget Eclipse and avoid it. Please use IntelliJ IDEA . This is very user friendly IDE for Java Spring MVC framework and also show what wrong you do.

  2. Create new project and used hibernate-core 4.0.1.Final version dependency at pom.xml file and also used 4.2.8.RELEASE version of own, spring-core and spring-orm dependencies.

    1. Remove import org.hibernate.Query.query; package from ProductDaoImpl.java class and put import org.hibernate.Query package.

Thank you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM