java - 没有 XML 的 Spring + Hibernate。错误 : NoSuchBeanDefinitionException

标签 java mysql spring hibernate spring-mvc

我正在自学 Spring 和 Hibernate。我读过几篇文章并尝试创建完全没有 XML 的 Spring 和 Hibernate 应用程序。我不知道为什么,但它不起作用,最后我收到错误消息:

 17:28:32.845 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
 17:28:32.854 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
 17:28:32.854 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
 17:28:32.928 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
 17:28:32.931 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
 17:28:32.937 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [com/boris/] to resources []
 17:28:32.937 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:com/boris/**/*.class] to resources []
 17:28:32.944 [main] INFO org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7382f612: startup date [Mon Aug 14 17:28:32 EEST 2017]; root of context hierarchy
 17:28:32.946 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext@7382f612: org.springframework.beans.factory.support.DefaultListableBeanFactory@5702b3b1: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory]; root of factory hierarchy
 17:28:32.965 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
 17:28:32.966 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
 17:28:33.003 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' to allow for resolving potential circular references
 17:28:33.009 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
 17:28:33.065 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
 17:28:33.065 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
 17:28:33.067 [main] INFO org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
 17:28:33.067 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor' to allow for resolving potential circular references
 17:28:33.067 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
 17:28:33.068 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
 17:28:33.074 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
 17:28:33.091 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor' to allow for resolving potential circular references
 17:28:33.091 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
 17:28:33.092 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
 17:28:33.092 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
 17:28:33.109 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor' to allow for resolving potential circular references
 17:28:33.109 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
 17:28:33.109 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor'
  17:28:33.109 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor'
  17:28:33.111 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor' to allow for resolving potential circular references
  17:28:33.111 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor'
  17:28:33.111 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
 17:28:33.111 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
 17:28:33.112 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor' to allow for resolving potential circular references
 17:28:33.112 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
 17:28:33.112 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor'
 17:28:33.112 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor'
  17:28:33.114 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor' to allow for resolving potential circular references
 17:28:33.114 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor'
 17:28:33.119 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@27808f31]
 17:28:33.126 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@6b57696f]
 17:28:33.127 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5702b3b1: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
 17:28:33.127 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
 17:28:33.127 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
 17:28:33.127 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
 17:28:33.127 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
  17:28:33.127 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor'
  17:28:33.128 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
  17:28:33.128 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.event.internalEventListenerProcessor'
  17:28:33.140 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.event.internalEventListenerProcessor' to allow for resolving potential circular references
   17:28:33.187 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.event.internalEventListenerProcessor'
   17:28:33.187 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
   17:28:33.187 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.event.internalEventListenerFactory'
   17:28:33.188 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.event.internalEventListenerFactory' to allow for resolving potential circular references
   17:28:33.196 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.event.internalEventListenerFactory'
    17:28:33.196 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
  17:28:33.197 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor'
   17:28:33.197 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
  17:28:33.248 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@2641e737]
  17:28:33.249 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
  17:28:33.252 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemProperties]
  17:28:33.252 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemEnvironment]
  17:28:33.253 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source. Returning [null]
 Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'employeeService' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at        org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1060)
at Test.main(Test.java:18)
   org.springframework.context.annotation.AnnotationConfigApplicationContext@7382f612: startup date [Mon Aug 14 17:28:32 EEST 2017]; root of context hierarchy

 Process finished with exit code 1

我正在努力找出我做错了什么。但不幸的是,我没有发现我的代码有任何问题。请你帮助我好吗? 下面是我的完整代码。

应用配置

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;


@Import({RepositoryConfig.class})
@Configuration
public class AppConfig
{
@Bean
public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
{
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ppc.setLocation(new ClassPathResource("application.properties"));
    ppc.setIgnoreUnresolvablePlaceholders(true);
    return ppc;
}
}

员工

 import javax.persistence.*;

 @Entity
 @Table(name = "tasks_test.employee_example")
public class Employee {
@Id @GeneratedValue
@Column(name = "id")
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "salary")
private int salary;

public Employee() {}

public Employee(Integer id, String firstName, String lastName, int salary)
{
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.salary = salary;
}


public int getId() {
    return id;
}
public void setId( int id ) {
    this.id = id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName( String first_name ) {
    this.firstName = first_name;
}
public String getLastName() {
    return lastName;
}
public void setLastName( String last_name ) {
    this.lastName = last_name;
}
public int getSalary() {
    return salary;
}
public void setSalary( int salary ) {
    this.salary = salary;
}

@Override
public String toString()
{
    return "User [firstName=" + firstName + ", lastName=" + lastName + ", id=" + id + ", salary=" + salary+ "]";
}
}

员工资料库

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.orm.hibernate4.HibernateTemplate;
 import org.springframework.stereotype.Repository;
 import org.springframework.transaction.annotation.Transactional;


 @Transactional
 @Repository
 public class EmployeeRepository
{
@Autowired
private HibernateTemplate hibernateTemplate;

public List<Employee> getAllEmployees()
{
    return this.hibernateTemplate.loadAll(Employee.class);
}

public Integer createEmployee(Employee employee)
{
    Employee mergeEmployee = this.hibernateTemplate.merge(employee);
    return mergeEmployee.getId();
}
}

员工服务

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class EmployeeService
{
@Autowired
private EmployeeRepository employeeRepository;

public List<Employee> getAllEmployees()
{
    return this.employeeRepository.getAllEmployees();
}

public Integer createEmployee(Employee employee)
{
    return this.employeeRepository.createEmployee(employee);
}
}

存储库配置

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.jdbc.datasource.DriverManagerDataSource;
 import org.springframework.orm.hibernate4.HibernateTemplate;
  import org.springframework.orm.hibernate4.HibernateTransactionManager;
 import org.springframework.orm.hibernate4.LocalSessionFactoryBean;



  @Configuration
 public class RepositoryConfig
 {

@Value("${jdbc.driverClassName}")     private String driverClassName;
@Value("${jdbc.url}")                 private String url;
@Value("${jdbc.username}")             private String username;
@Value("${jdbc.password}")             private String password;

@Value("${hibernate.dialect}")         private String hibernateDialect;
@Value("${hibernate.show_sql}")     private String hibernateShowSql;
@Value("${hibernate.hbm2ddl.auto}") private String hibernateHbm2ddlAuto;

@Bean()
public DataSource getDataSource()
{
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)
{
    HibernateTransactionManager htm = new HibernateTransactionManager();
    htm.setSessionFactory(sessionFactory);
    return htm;
}

@Bean
@Autowired
public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory)
{
    HibernateTemplate hibernateTemplate = new       HibernateTemplate(sessionFactory);
    return hibernateTemplate;
}

@Bean
public LocalSessionFactoryBean getSessionFactory()
{
    LocalSessionFactoryBean asfb = new LocalSessionFactoryBean();
    asfb.setDataSource(getDataSource());
    asfb.setHibernateProperties(getHibernateProperties());
    asfb.setPackagesToScan(new String[]{"com.boris"});
    return asfb;
}

@Bean
public Properties getHibernateProperties()
{
    Properties properties = new Properties();
    properties.put("hibernate.dialect", hibernateDialect);
    properties.put("hibernate.show_sql", hibernateShowSql);
    properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
    return properties;
}

}

测试

 import java.util.List;
 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 import org.springframework.context.annotation.ComponentScan;


 @ComponentScan("com.boris")
 public class Test
{
public static void main(String[] args)
{
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.scan("com.boris");
    ctx.refresh();

    System.out.println(ctx);
    EmployeeService employeeService = ctx.getBean("employeeService",EmployeeService.class);



    Employee employee1 = new Employee(null, "Bob", "Marley", 16000);
    Employee employee2 = new Employee(null, "Donald", "Trump", 12000);
    Employee employee3 = new Employee(null, "Olga","Lifshitz", 8000);
    Employee employee4 = new Employee(null, "Massimo", "Dutti", 7000);
    int id1 = employeeService.createEmployee(employee1);
    System.out.println("New Employee created with ID="+id1);
    int id2 = employeeService.createEmployee(employee2);
    System.out.println("New Employee created with ID="+id2);
    int id3 = employeeService.createEmployee(employee3);
    System.out.println("New Employee created with ID="+id3);
    int id4 = employeeService.createEmployee(employee4);
    System.out.println("New Employee created with ID="+id4);
    List<Employee> everybody = employeeService.getAllEmployees();
    for (Employee e : everybody)
    {
        System.out.println(e);
    }
}

}

应用程序属性

  jdbc.driverClassName=org.hsqldb.jdbcDriver
  jdbc.url=jdbc:mysql://localhost:3306/tasks_test
 jdbc.username=user
 jdbc.password=pass


 hibernate.dialect=org.hibernate.dialect.HSQLDialect
 hibernate.show_sql=true
 hibernate.hbm2ddl.auto=update
 hibernate.generate_statistics=true

最佳答案

你能尝试像那样初始化 employeeService 吗

@Autowired EmployeeService employeeService

在测试课上。

关于java - 没有 XML 的 Spring + Hibernate。错误 : NoSuchBeanDefinitionException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45677468/

相关文章:

mysql - AWS SimpleDB 的 MSSQL/MySQL 支持

php - Laravel 中使用 Eloquent 的存储库模式

java - 为什么 tomcat 服务器在 eclipse 中无法正常启动?

java - 是否有工具可以发现类路径中的多个 jar 中是否存在同一个类?

java - 获取 OutOfMemoryError : GC overhead limit exceeded with Tomcat server in Linux machine

java - 在java中解析JSON

spring - JdbcDaoSupport 是做什么用的?

java - 使用 java datetimeformatter 从星期几解析日期

C# MySql如何将存储过程与dataGridView绑定(bind)

spring - 如何在没有注释的情况下对 spring MVC cron 进行编程