首页 > 解决方案 > 在 @Repository 类上使用 .getBean()

问题描述

我目前正在学习 Spring 和 Hibernate。我有一个包含所有数据库查询的 StudentDAOImpl 类。我想在我的 main 函数中获取这个 bean 的实例,并在我的 main 函数中运行查询方法进行测试。我试图通过调用 getBean() 方法来做到这一点,因为 bean 的名称是类,但如果我没记错的话,第一个字母是小写的。编译器给了我这个错误

Exception in thread "main org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'studentDAOImpl' available**

为什么 Spring 找不到我的 StudentDAOImpl bean?感谢您花时间阅读这篇文章。这是我的代码

主功能

   public static void main(String[] args) {

        ApplicationContext ctx = new AnnotationConfigApplicationContext(AnimalConfig.class,HibernateConfig.class); // Makes the sessionFactory bean known to the IOC
        StudentDAOImpl student = (StudentDAOImpl)ctx.getBean("studentDAOImpl");
        Student aStudent = new Student("dasdasdas","dasdadas","dsadasdasda@gmail.com");
        student.addStudent(aStudent);
    
        (( ConfigurableApplicationContext )ctx).close();  //Close the applicationContext
        SpringApplication.run(DemoApplication.class, args);    

    }

StudentDAOImpl 类

@Repository  //Sets up componenent scanning for DI for our services
public class StudentDAOImpl implements StudentDAO{

    @Autowired
    SessionFactory sessionFactory;
    //Queries Ommited from post for space saving purposes
}

休眠配置文件

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

@Bean(name = "sessionFactory")
@Scope("singleton")
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(packagesToScan());
    sessionFactory.setHibernateProperties(hibernateProperties());

    return sessionFactory;
}

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/demo");
    dataSource.setUsername("root");
    dataSource.setPassword("danielL45");

    return dataSource;
}

@Bean
public PlatformTransactionManager hibernateTransactionManager() {
    HibernateTransactionManager transactionManager
      = new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactory().getObject());
    return transactionManager;
}

private String[] packagesToScan(){
  return new String[] {
    "com.example.demo.Entities.Student"
  };
}
private final Properties hibernateProperties() {
    Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
    hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    hibernateProperties.setProperty("current_session_context_class", "thread");
    return hibernateProperties;
}

}

标签: javaspringhibernate

解决方案


Use this:

StudentDAOImpl student = ctx.getBean(StudentDAOImpl.class)

This is a more secure way to get the bean that we need, since we may have only one bean with this class, using a string to select a Spring Bean has a propability of not working when not writing the name correctly.


推荐阅读