即使提供了Bean,SessionFactory也不会自动接线 [英] SessionFactory not autowired even with Beans provided

查看:64
本文介绍了即使提供了Bean,SessionFactory也不会自动接线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

集成了Spring Boot和Hibernate,但是SessionFactory自动装配存在问题,因为它表示未提供bean,但在Configuration类中提供了@Bean.

Integrating spring boot and hibernate but there is an issue with SessionFactory autowiring as it is saying that beans are not provided but @Bean is provided in the Configuration class.

请看一下代码.

由于我在使用SessionFactory自动装配时遇到问题,因此尚未提供Dao层.

Dao layer was not provided yet as i'm having issue with SessionFactory autowiring.

主要应用程序类别

package com.ctechm.ctec;

 import java.util.Arrays;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.repository.CrudRepository;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import com.ctechm.ctec.service.ServiceImpl;

@SpringBootApplication
public class CtecApplication implements CommandLineRunner{

 @Autowired
private ApplicationContext appContext;

@Autowired 
Text text;

@Autowired
ServiceImpl serviceImpl;
@Autowired
SessionFactory sessionFactory;

public static void main(String[] args) {
    SpringApplication.run(CtecApplication.class);
}

   }

上面的代码中提供了

@Autowired注释,并且在Configuration类中定义了它们的@Bean.对于除SessionFactory之外的所有自动装配,它都可以正常工作.

@Autowired Annotations are provided in the above code and their @Bean is defined in the Configuration class.It is working fine for all Autowirings except for SessionFactory.

配置类

 package com.ctechm.ctec;

 import java.util.Properties;

 import javax.persistence.EntityManagerFactory;
 import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Configuration {

 @Bean
 public Text text() {
    return new Text();
 }


@Bean
public Text texter(){
    return new Text();
}

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/scm");
        dataSource.setUsername("root");
        dataSource.setPassword("password");
        return dataSource;
     }

 @Bean
public LocalSessionFactoryBean sessionFactory() {
    Properties properties = new Properties();
    LocalSessionFactoryBean bean=new LocalSessionFactoryBean();
     bean.setDataSource(dataSource());
         properties.setProperty("hibernate.connection.url","jdbc:mysql://localhost:3306/scm");      properties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLDialect"); 
         properties.setProperty("hibernate.hbm2ddl.auto", "update");
       properties.setProperty("hibernate.connection.username","root");
       properties.setProperty("hibernate.connection.password","password");
       bean.setHibernateProperties(properties);
     return bean;
    }

     }

服务等级

package com.ctechm.ctec.service;

import java.lang.annotation.Annotation;

 import com.ctechm.ctec.service.Service;

@Service   
public class ServiceImpl implements Service {


 }

application.properties

application.properties

 spring.datasource.url=jdbc:mysql://localhost:3306/scm
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.hibernate.ddl-auto=none

POM.XML

    <?xml version="1.0" encoding="UTF-8"?>
   <project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

<groupId>com.ctechm</groupId>
<artifactId>ctec</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>ctec</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
     </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
     </dependency>
    </dependencies>

  <build>
     <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
 </build>


 </project>

每当我启动控制台时都会出现这样的错误

When ever i start the console getting error like this

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jpaContext': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.Set<javax.persistence.EntityManager>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1276) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1133) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at com.ctechm.ctec.CtecApplication.main(CtecApplication.java:33) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.Set<javax.persistence.EntityManager>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    ... 19 common frames omitted

请看看并建议我需要做哪些更改. 一件事是当我删除bean并自动装配sessionFactory时,一切工作正常.我尝试了stackoverflow中的所有帖子,但无法找出解决方案.

Please have a look and suggest me what changes need to be done. One thing was when i remove bean and autowiring of sessionFactory everything was working fine.I tried from all the posts in stackoverflow but was not able to figure out the solution.

推荐答案

从您发布的代码中,您尚不清楚要在此处实现什么. 使用spring-boot和spring-data,您基本上可以使用最低配置启动应用程序.

From the code you posted it is not clear what you want to achieve here. Using spring-boot and spring-data you basically can start the app with minimum configuration.

在这种情况下,您可以跳过Configuration.java并使用可以直接添加到application.properties文件中的Common Spring Boot属性来配置数据库访问.

In your case you can skip the Configuration.java and configure the database access using the Common Spring Boot properties which you can add directly in the application.properties file.

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/scm?useSSL=false
spring.datasource.username = spring-test
spring.datasource.password = root


## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

不需要自动装配SessionFactory,而是可以添加一个Repository接口,该接口将扩展JpaRepository接口.该接口已经具有基本CRUD操作的定义. 这是一个示例,看起来像这样.

Autowiring SessionFactory is not needed, instead you can add a Repository interface which will extend the JpaRepository interface. This interface already has definitions for the basic CRUD operations. Here is an example of how that should look like.

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface CtecRepository extends JpaRepository<CtecEntity, String> {

   List<CtecEntity> findByName(String name);
}

比起将存储库注入Service类,您就可以从那里使用数据库了.

Than you can Inject your Repository to a Service class and from there you can work with the database.

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

import java.util.List;

@Service
public class CtecService {

@Autowired
private CtecRepository ctecRepository;


public void create() {
    CtecEntity entity = new CtecEntity();
    entity.setName("test name");
    ctecRepository.save(entity);
}


public List<CtecEntity> getAllByName(String name) {
    return ctecRepository.findByName(name);
}
}

CtecEntity.java

CtecEntity.java

import javax.persistence.Id;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;

@Entity
@Table(name = "ctec")
public class CtecEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}
}

这篇关于即使提供了Bean,SessionFactory也不会自动接线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆