Spring Boot 请考虑在配置中定义类型为“com.repository.UserRepository”的Bean

dffbzjpn  于 2022-12-29  发布在  Spring
关注(0)|答案(6)|浏览(153)

你好,我在Spring Boot 时使用Java配置进行JPA和Hibernate配置,我被这个错误卡住了几个小时。即使我已经将UserRepository声明为Bean,它仍然无法获取存储库。

package com.repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

正在使用此资料档案库的我的服务类:

package com.service;

@Service
public class AppointmentPaymentServiceImpl implements AppointmentPaymentService {

@Autowired
private UserRepository userRepository;
......
......
}

我的数据库配置:

package com.config;

@Configuration
@PropertySource(value = { "classpath:application.properties" })
@EnableTransactionManagement
@EnableJpaRepositories("com.repository.*")
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
public class DBConfig {

@Value("${spring.datasource.driver-class-name}")
public String driver;

@Value("${spring.datasource.url}")
public String url;

@Value("${spring.datasource.username}")
public String username;

@Value("${spring.datasource.password}")
public String password;

@Value("${spring.jpa.properties.hibernate.dialect}")
public String dialect;

@Value("${spring.jpa.hibernate.ddl-auto}")
public String ddl;

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);

    return dataSource;
}

@Bean(name = "sessionFactory")
public LocalSessionFactoryBean hibernateSessionFactory(DataSource dataSource) {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.model.*" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

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

/*@Bean
@Qualifier(value = "entityManager")
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
    return entityManagerFactory.createEntityManager();
}*/

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

@Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
 vendorAdapter.setDatabase(Database.MYSQL);
 vendorAdapter.setGenerateDdl(true);

 LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
 em.setDataSource(dataSource());
 em.setPackagesToScan("com.model.*");
em.setJpaVendorAdapter(vendorAdapter);
 em.setJpaProperties(hibernateProperties());

 return em;
}

@Bean
 public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
 JpaTransactionManager transactionManager = new JpaTransactionManager();
 transactionManager.setEntityManagerFactory(emf);

 return transactionManager;
}

Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty("hibernate.hbm2ddl.auto", ddl);
            setProperty("hibernate.connection.useUnicode", "true");
            setProperty("spring.jpa.hibernate.ddl-auto", ddl);
            setProperty("hibernate.dialect", dialect);
            setProperty("spring.jpa.properties.hibernate.dialect", dialect);
            setProperty("hibernate.globally_quoted_identifiers", "true");
            setProperty("hibernate.connection.CharSet", "utf8mb4");
            setProperty("hibernate.connection.characterEncoding", "utf8");

        }
    };
}

}

这是我的主要课程

package com; 

@SpringBootApplication
@ComponentScan(basePackages = { "com.*"})
@EnableCaching
@Configuration
@PropertySource({"classpath:logging.properties"})
public class MainApplication {

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

}

我的pom.xml包含了hib和jpa的这些依赖项,如果我只使用spring数据jpa,那么默认情况下会导入hibernate-core 5.0.12.Final,这是我不希望的:

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
    </dependency>
    .
    .
    .
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>
  </dependencies>

错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userRepository in com.service.AppointmentPaymentServiceImpl required a bean of type 'com.repository.UserRepository' that could not be found.

Action:

Consider defining a bean of type 'com.repository.UserRepository' in your configuration.

我的用户实体:

package com.model;

@Entity
@Table(name = "USER")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "id")
private Long id;

@NotNull
@Column(name = "city_id")
private Long cityId;

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

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

@Column(name = "locality")
private String locality;

@Column(name = "gender")
private String gender;

}
lo8azlld

lo8azlld1#

在主要的spring Boot 应用程序类中添加以下注解解决了我的案例中的问题:
@Component 扫描(“com.myapp.存储库”)

wko9yo5t

wko9yo5t2#

您的@EnableJpaRepositories注解是错误的。您没有定义以这种方式找到仓库的包。
假设它们所在的包名为:
foo.somepackage.repositories,则注解应为@EnableJpaRepositories("foo.somepackage.repositories")
尝试更正注解,以便正确地扫描您的存储库包,从而将它们纳入上下文。

tyu7yeag

tyu7yeag3#

我认为你的代码必须组织在com.xyz.abc.model@EnableJpaRepostiories应该工作。例如:com.xyz.abc.repositorycom.xyz.abc.service

kq0g1dla

kq0g1dla4#

只要把AppointmentPaymentServiceImplUserRepository放在同一个包中,对我来说就是com.

tp5buhyn

tp5buhyn5#

我也遇到了同样的问题。我刚把仓库从我的工作项目复制到一个新项目中,我得到了同样的错误。考虑定义一个类型为com.[packagename]. repository.[repository-name]的bean。上面的方法对我都不起作用,后来我做了以下事情:
1.删除了POM文件中JPA的版本依赖性(仅删除了版本标记)
1.我使用的是Java 15,当我从www.example.com创建SpringBoot项目时start.spring.io,只有11和16个fava版本,所以我选择了11作为我的项目,我也在POM文件中更改了它
15(之前是11)
1.现在我删除了主文件中的@ComponentScan注解,这也是我早期使用的解决方案。
1.只需该高速缓存无效并重新启动
1.类型mvn清洁安装

  1. mvn clean spring-boot:run希望这对你也有用
e37o9pze

e37o9pze6#

在你的springboot应用程序的主类中添加以下任意一个注解,这两个注解对我都有效。

@ComponentScan("com.abc.repository")
@EnableAutoConfiguration

相关问题