Не удалось найти класс репозитория bean entityManagerFactory - PullRequest
0 голосов
/ 24 сентября 2019

Я создаю приложение angular + spring и пытаюсь развернуть его на том же сервере.когда я создал бэкэнд отдельно, он работал нормально, весь процесс работал.но когда я скопировал свой угловой проект в весенний проект и настроил его в pom.xml, обновил свой maven и попытался запустить проект, он начал выдавать ошибку ниже

 .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.8.RELEASE)

2019-09-24 16:13:29.074  INFO 3136 --- [           main] 
com.accounts.rtgsneft.Application        : Starting Application on HO-W- 
Ankushpc with PID 3136 (D:\Rocky\workspaces\acounts-projects\rtgs-neft- 
v1.0\target\classes started by Rocky in D:\Rocky\workspaces\acounts- 
projects\rtgs-neft-v1.0)
2019-09-24 16:13:29.076  INFO 3136 --- [           main] 
com.accounts.rtgsneft.Application        : No active profile set, falling 
back to default profiles: default
2019-09-24 16:13:29.530  INFO 3136 --- [           main] 
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data 
repositories in DEFAULT mode.
2019-09-24 16:13:29.584  INFO 3136 --- [           main] . 
s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository 
scanning in 48ms. Found 4 repository interfaces.
2019-09-24 16:13:29.910  INFO 3136 --- [           main] 
trationDelegate$BeanPostProcessorChecker : Bean 
'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$3c9c44bd] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-24 16:13:30.143  INFO 3136 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8086 (http)
2019-09-24 16:13:30.160  INFO 3136 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-09-24 16:13:30.160  INFO 3136 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.24]
2019-09-24 16:13:30.264  INFO 3136 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-09-24 16:13:30.264  INFO 3136 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1158 ms
2019-09-24 16:13:30.399  WARN 3136 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'beneficiaryController': Unsatisfied dependency expressed through field 'beneficiaryService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'beneficiaryMasterServiceImpl': Unsatisfied dependency expressed through field 'beneficiaryRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beneficiaryMasterRepository': Cannot create inner bean '(inner bean)#3ac04654' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3ac04654': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2019-09-24 16:13:30.402  INFO 3136 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-09-24 16:13:30.416  INFO 3136 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run 
your application with 'debug' enabled.
2019-09-24 16:13:30.465 ERROR 3136 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field beneficiaryRepo in 
com.accounts.rtgsneft.service.BeneficiaryMasterServiceImpl required a bean 
named 'entityManagerFactory' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

, я перепробовал все решения в стеке, но ни одногоиз них работали.

Вот решения, которые я попробовал:

. Это решение, которое я попробовал при отладке.

my 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>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.accounts.rtgsneft</groupId>
<artifactId>rtgsneft</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rtgsneft</name>
<description>Gold's Gym Account department rtgs neft software</description>

<properties>
    <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-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </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>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${basedir}/src/main/resources/static/</outputDirectory>
                        <resources>
                            <resource>
                                <directory>${basedir}/src/main/rtgs-neft/dist/rtgs-neft</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</project>

my BeneficiaryController .java

package com.accounts.rtgsneft.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.accounts.rtgsneft.model.BeneficiaryMaster;
import com.accounts.rtgsneft.service.BeneficiaryMasterService;

/**
* @author Rocky
*
*/
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("beneficiary")
public class BeneficiaryController {

@Autowired
BeneficiaryMasterService beneficiaryService;

@GetMapping("all-beneficiary")
public ResponseEntity<?> getBeneficiaries() {
    List<BeneficiaryMaster> beneficiaries = beneficiaryService.gettingBeneficiaries();
    return new ResponseEntity<>(beneficiaries, HttpStatus.OK);
}

@PostMapping("new-beneficiary")
public ResponseEntity<?> postBeneficiary(@RequestBody BeneficiaryMaster beneficiary) {
    boolean beneficiaryRegistered = beneficiaryService.registerBeneficiary(beneficiary);
    return new ResponseEntity<>(beneficiaryRegistered, HttpStatus.OK);
}

@PostMapping("single-beneficiary")
public ResponseEntity<?> selectedBeneficiary(@RequestBody BeneficiaryMaster beneficiaryOBJ) {
    BeneficiaryMaster beneficiary = beneficiaryService.getBeneficiary(beneficiaryOBJ.getAccountNumber());
    return new ResponseEntity<>(beneficiary, HttpStatus.OK);
}
}

my BeneficiaryMasterService.java

package com.accounts.rtgsneft.service;

import java.util.List;

import com.accounts.rtgsneft.model.BeneficiaryMaster;
public interface BeneficiaryMasterService {
List<BeneficiaryMaster> gettingBeneficiaries();
boolean registerBeneficiary(BeneficiaryMaster beneficiary);
BeneficiaryMaster getBeneficiary(Long accountNumber);
}

my BeneficiaryMasterServiceImpl.java

package com.accounts.rtgsneft.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.accounts.rtgsneft.model.BeneficiaryMaster;
import com.accounts.rtgsneft.repos.BeneficiaryMasterRepository;
@Service
public class BeneficiaryMasterServiceImpl implements BeneficiaryMasterService {

@Autowired
BeneficiaryMasterRepository beneficiaryRepo;

@Override
public List<BeneficiaryMaster> gettingBeneficiaries() {     
    return beneficiaryRepo.findAll();
}

@Override
public boolean registerBeneficiary(BeneficiaryMaster beneficiary) {

    boolean benficiaryStatusFlag = false;
    BeneficiaryMaster benficiaryStatus= beneficiaryRepo.save(beneficiary);
    if(benficiaryStatus != null ) {
        benficiaryStatusFlag = true;
    }
    return benficiaryStatusFlag;
}

@Override
public BeneficiaryMaster getBeneficiary(Long accountNumber) {
    return beneficiaryRepo.getOne(accountNumber);
}
}

my BeneficiaryMasterRepository.java

package com.accounts.rtgsneft.repos;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.accounts.rtgsneft.model.BeneficiaryMaster;
@Repository
public interface BeneficiaryMasterRepository extends 
JpaRepository<BeneficiaryMaster, Long> {}

Надеюсь, этого достаточно для выяснения проблемы.

Если есть другое решение, пожалуйста, порекомендуйте его мне.Я использую Spring 2.17. Я хочу развернуть файл war приложения в tomcat, и перед тем, как это сделать, я должен проверить его на предмет того, работает ли он по-прежнему или нет.

1 Ответ

0 голосов
/ 24 сентября 2019

Spring Data JPA по умолчанию ищет EntityManagerFactory с именем entityManagerFactory.Посмотрите эту часть Javadoc EnableJpaRepositories или Таблицу 2.1 документации JPA Spring Data.

Это означает, что вам нужно либо переименовать ваш компонент emf в entityManagerFactory, либо изменить конфигурацию Spring на:

(если вы используете XML)

или

@ EnableJpaRepositories (basePackages = "your.package", entityManagerFactoryRef = "emf")

(если вы используете JavaConfig)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...