我终于找到了问题的原因。它不像错误注释所示那样清晰。这是由我的MyTutorialWebAppInitializer
引起的。
以前是这样的:
public class MyTutorialWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
protected String[] getServletMappings() {
return new String[]{"/home/","/about/"};
}
}
我更改如下,现在一切正常!
public class MyTutorialWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/about/","/home/");
}
}
嗨,我是JEE网站开发的新手。我正在使用Spring MVC和Hibernate来连接MySql数据库。 Fowlloing是我第一次访问数据库的直接例子,但是我在相当长的一段时间里一直陷入编译错误。任何建议将不胜感激。
错误信息:
> Caused by: org.springframework.beans.factory.BeanCreationException: Error
> creating bean with name 'puzzleServiceImpl': Injection of autowired
> dependencies failed; nested exception is
> org.springframework.beans.factory.BeanCreationException: Could not
> autowire field: private com.mytutorial.dao.PuzzleDAO
> com.mytutorial.service.impl.PuzzleServiceImpl.puzzleDAO; nested
> exception is org.springframework.beans.factory.BeanCreationException:
> Error creating bean with name 'puzzleDAOImpl': Injection of autowired
> dependencies failed; nested exception is
> org.springframework.beans.factory.BeanCreationException: Could not
> autowire field: private org.hibernate.SessionFactory
> com.mytutorial.dao.impl.PuzzleDAOImpl.sessionFactory; nested exception
> is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type [org.hibernate.SessionFactory] 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)}
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
> at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122)
> at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
> at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
> at
> org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
> at
> org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
> at
> org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
> at
> org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:910)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:853)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
> ... 60 more Caused by:
> org.springframework.beans.factory.BeanCreationException: Could not
> autowire field: private com.mytutorial.dao.PuzzleDAO
> com.mytutorial.service.impl.PuzzleServiceImpl.puzzleDAO; nested
> exception is org.springframework.beans.factory.BeanCreationException:
> Error creating bean with name 'puzzleDAOImpl': Injection of autowired
> dependencies failed; nested exception is
> org.springframework.beans.factory.BeanCreationException: Could not
> autowire field: private org.hibernate.SessionFactory
> com.mytutorial.dao.impl.PuzzleDAOImpl.sessionFactory; nested exception
> is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type [org.hibernate.SessionFactory] 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)}
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
> at
> org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
> ... 71 more Caused by:
> org.springframework.beans.factory.BeanCreationException: Error
> creating bean with name 'puzzleDAOImpl': Injection of autowired
> dependencies failed; nested exception is
> org.springframework.beans.factory.BeanCreationException: Could not
> autowire field: private org.hibernate.SessionFactory
> com.mytutorial.dao.impl.PuzzleDAOImpl.sessionFactory; nested exception
> is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type [org.hibernate.SessionFactory] 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)}
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
> at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122)
> at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
> at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
> at
> org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
> at
> org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
> at
> org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
> at
> org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:910)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:853)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
> ... 73 more Caused by:
> org.springframework.beans.factory.BeanCreationException: Could not
> autowire field: private org.hibernate.SessionFactory
> com.mytutorial.dao.impl.PuzzleDAOImpl.sessionFactory; nested exception
> is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type [org.hibernate.SessionFactory] 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)}
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
> at
> org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
> ... 84 more Caused by:
> org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type [org.hibernate.SessionFactory] 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)}
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
> at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
> at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
> ... 86 more
DataPuzzle.java:
package com.mytutorial.data;
import javax.persistence.*;
/**
* Created by bjhl on 11/16/16.
*/
@Entity
@Table(name = "puzzles")
public class DataPuzzle {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "title")
private String title;
@Column(name = "author")
private String author;
@Column(name = "price")
private float price;
public Integer getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public float getPrice() {
return price;
}
public void setId(Integer id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setPrice(float price) {
this.price = price;
}
}
PuzzleDAO:
public interface PuzzleDAO {
public void addPuzzle(DataPuzzle dataPuzzle);
public List<DataPuzzle> getPuzzles();
public void removePuzzle(Integer id);
}
PuzzleDAOImpl
package com.mytutorial.dao.impl;
import com.mytutorial.dao.PuzzleDAO;
import com.mytutorial.data.DataPuzzle;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
;
/**
* Created by bjhl on 11/16/16.
*/
@Repository
public class PuzzleDAOImpl implements PuzzleDAO {
@Autowired
private SessionFactory sessionFactory;
public void addPuzzle(DataPuzzle dataPuzzle) {
sessionFactory.getCurrentSession().save(dataPuzzle);
}
public List<DataPuzzle> getPuzzles() {
return sessionFactory.getCurrentSession().createQuery("from DataPuzzle")
.list();
}
public void removePuzzle(Integer id) {
DataPuzzle puzzle = (DataPuzzle) sessionFactory.getCurrentSession().load(
DataPuzzle.class, id);
if (null != puzzle) {
sessionFactory.getCurrentSession().delete(puzzle);
}
}
}
PuzzleService:
package com.mytutorial.service;
import com.mytutorial.data.DataPuzzle;
import java.util.List;
/**
* Created by bjhl on 11/16/16.
*/
public interface PuzzleService {
public void addPuzzle(DataPuzzle dataPuzzle);
public List<DataPuzzle> getPuzzles();
public void removePuzzle(Integer id);
}
PuzzleServiceImpl
package com.mytutorial.service.impl;
import com.mytutorial.dao.PuzzleDAO;
import com.mytutorial.data.DataPuzzle;
import com.mytutorial.service.PuzzleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by bjhl on 11/16/16.
*/
@Service
public class PuzzleServiceImpl implements PuzzleService {
@Autowired
private PuzzleDAO puzzleDAO;
@Transactional
public void addPuzzle(DataPuzzle dataPuzzle) {
puzzleDAO.addPuzzle(dataPuzzle);
}
@Transactional
public List<DataPuzzle> getPuzzles() {
return puzzleDAO.getPuzzles();
}
@Transactional
public void removePuzzle(Integer id) {
puzzleDAO.removePuzzle(id);
}
}
WebConfig
package com.mytutorial.config;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;
/**
* Created by bjhl on 11/15/16.
*/
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.mytutorial")
@PropertySource("classpath:jdbc.properties")
public class WebConfig{
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
@Resource
private Environment env;
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".html");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
}
如果从
@Autowired
中删除PuzzleDAOImpl
,则编译错误将消失,但这将导致数据库连接出现其他问题。谁能救我! 最佳答案
您需要在代码中进行以下修复,
@Service
public class PuzzleServiceImpl implements PuzzleService {
它应该是,
@Service("puzzleService")
public class PuzzleServiceImpl implements PuzzleService {
DAO /存储库组件也是如此,
@Repository
public class PuzzleDAOImpl implements PuzzleDAO {
它应该是
@Repository("puzzleDAO")
public class PuzzleDAOImpl implements PuzzleDAO {
编辑:尝试按照以下方式使会话工厂合格,
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}