java - NoSuchBeanDefinitionException:没有名为“persistenceUnit”的bean可用
问题描述
我坚持这一点,我从这里尝试了许多类似的解决方案
我在 Wildfly 11 中部署了一个 Spring Boot 应用程序
这是部署错误:
"{\"WFLYCTL0080: Failed services\" => {\"jboss.undertow.deployment.default-server.default-host./myapp\" => \"java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'canalesController': Unsatisfied dependency expressed through field 'list'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CeEncuestasList': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'persistenceUnit' available
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'canalesController': Unsatisfied dependency expressed through field 'list'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CeEncuestasList': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'persistenceUnit' available
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'canalesController': Unsatisfied dependency expressed through field 'list'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CeEncuestasList': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'persistenceUnit' available
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CeEncuestasList': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'persistenceUnit' available
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'persistenceUnit' available\"}}"
控制台部署:
14:39:55,146 INFO [org.jboss.as.jpa] (MSC service thread 1-5) WFLYJPA0002: Read persistence.xml for persistenceUnit
14:39:55,437 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 62) WFLYJPA0010: Starting Persistence Unit (phase 1 of 2) Service 'myapp.war#persistenceUnit'
14:39:55,457 INFO [org.hibernate.jpa.internal.util.LogHelper] (ServerService Thread Pool -- 62) HHH000204: Processing PersistenceUnitInfo [
name: persistenceUnit
...]
14:39:55,536 INFO [org.hibernate.Version] (ServerService Thread Pool -- 62) HHH000412: Hibernate Core {5.1.10.Final}
14:39:55,538 INFO [org.hibernate.cfg.Environment] (ServerService Thread Pool -- 62) HHH000206: hibernate.properties not found
14:39:55,538 INFO [org.hibernate.cfg.Environment] (ServerService Thread Pool -- 62) HHH000021: Bytecode provider name : javassist
14:39:55,588 INFO [org.hibernate.annotations.common.Version] (ServerService Thread Pool -- 62) HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
14:39:55,659 WARN [org.jboss.as.ee] (MSC service thread 1-1) WFLYEE0007: Not installing optional component org.springframework.http.server.reactive.ServletServerHttpResponse$ResponseAsyncListener due to an exception (enable DEBUG log level to see the cause)
14:39:55,667 WARN [org.jboss.as.ee] (MSC service thread 1-1) WFLYEE0007: Not installing optional component org.springframework.http.server.reactive.ServletHttpHandlerAdapter$HandlerResultAsyncListener due to an exception (enable DEBUG log level to see the cause)
14:39:55,669 WARN [org.jboss.as.ee] (MSC service thread 1-1) WFLYEE0007: Not installing optional component org.springframework.http.server.ServletServerHttpAsyncRequestControl due to an exception (enable DEBUG log level to see the cause)
14:39:55,669 WARN [org.jboss.as.ee] (MSC service thread 1-1) WFLYEE0007: Not installing optional component org.springframework.web.context.request.async.StandardServletAsyncWebRequest due to an exception (enable DEBUG log level to see the cause)
14:39:55,669 WARN [org.jboss.as.ee] (MSC service thread 1-1) WFLYEE0007: Not installing optional component org.springframework.http.server.reactive.ServletServerHttpRequest$RequestAsyncListener due to an exception (enable DEBUG log level to see the cause)
14:39:55,719 INFO [org.infinispan.factories.GlobalComponentRegistry] (MSC service thread 1-7) ISPN000128: Infinispan version: Infinispan 'Chakra' 8.2.8.Final
14:39:55,749 WARN [org.jboss.weld.deployer] (MSC service thread 1-1) WFLYWELD0013: Deployment myapp.war contains CDI annotations but no bean archive was found (no beans.xml or class with bean defining annotations was present).
14:39:55,799 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 62) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'myapp.war#persistenceUnit'
14:39:55,949 WARN [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool -- 62) IJ000407: No lazy enlistment available for gisCexDS
14:39:55,964 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 62) HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL94Dialect
14:39:55,996 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 63) WFLYCLINF0002: Started client-mappings cache from ejb container
14:39:58,101 INFO [org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl] (ServerService Thread Pool -- 62) HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
14:39:58,101 INFO [org.hibernate.type.BasicTypeRegistry] (ServerService Thread Pool -- 62) HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@5c14ba5d
14:39:58,101 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (ServerService Thread Pool -- 62) Envers integration enabled? : true
14:39:58,339 INFO [org.hibernate.validator.internal.util.Version] (ServerService Thread Pool -- 62) HV000001: Hibernate Validator 5.3.5.Final
14:39:58,671 INFO [io.undertow.servlet] (ServerService Thread Pool -- 77) 2 Spring WebApplicationInitializers detected on classpath
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77)
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77) . ____ _ __ _ _
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77) /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77) ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77) \\/ ___)| |_)| | | | | || (_| | ) ) ) )
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77) ' |____| .__|_| |_|_| |_\__, | / / / /
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77) =========|_|==============|___/=/_/_/_/
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77) :: Spring Boot :: (v2.2.6.RELEASE)
14:39:59,072 INFO [stdout] (ServerService Thread Pool -- 77)
14:39:59,141 INFO [com.mytest.test.Application] (ServerService Thread Pool -- 77) Starting Application on PCSISSVA-ASU10 with PID 12568 (started by figuerel in C:\Users\figuerel\Downloads\wildfly-11.0.0.Final\wildfly-11.0.0.Final\bin)
14:39:59,141 INFO [com.mytest.test.Application] (ServerService Thread Pool -- 77) No active profile set, falling back to default profiles: default
14:39:59,458 INFO [org.springframework.data.repository.config.RepositoryConfigurationDelegate] (ServerService Thread Pool -- 77) Bootstrapping Spring Data JPA repositories in DEFAULT mode.
14:39:59,473 INFO [org.springframework.data.repository.config.RepositoryConfigurationDelegate] (ServerService Thread Pool -- 77) Finished Spring Data repository scanning in 6ms. Found 0 JPA repository interfaces.
14:39:59,874 INFO [io.undertow.servlet] (ServerService Thread Pool -- 77) Initializing Spring embedded WebApplicationContext
14:39:59,874 INFO [org.springframework.web.context.ContextLoader] (ServerService Thread Pool -- 77) Root WebApplicationContext: initialization completed in 717 ms
14:40:00,361 WARN [org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext] (ServerService Thread Pool -- 77) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'canalesController': Unsatisfied dependency expressed through field 'list'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CeEncuestasList': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'persistenceUnit' available
14:40:00,371 INFO [org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener] (ServerService Thread Pool -- 77)
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
14:40:00,391 ERROR [org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter] (ServerService Thread Pool -- 77)
***************************
APPLICATION FAILED TO START
***************************
Description:
Field list in com.mytest.test.controller.CanalesController required a bean named 'persistenceUnit' 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 'persistenceUnit' in your configuration.
14:40:00,391 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 77) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./myapp: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./myapp: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'canalesController': Unsatisfied dependency expressed through field 'list'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CeEncuestasList': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'persistenceUnit' available
这是我的pom
<?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.mytest</groupId>
<artifactId>myapp</artifactId>
<version>0.1.0</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<start-class>com.mytest.test.Application</start-class>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<!--exclusion para wildfly-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--exclusion para wildfly-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--para wildfly-->
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
<scope>test</scope>
</dependency>-->
<!--para wildfly-->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>11.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>
SpringBoot 应用程序
package com.mytest.test;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, XADataSourceAutoConfiguration.class})
@EnableJpaRepositories("com.mytest.test.repository")
public class Application extends SpringBootServletInitializer {
@Bean
public KeycloakSpringBootConfigResolver keycloakSpringBootConfigResolver(){
return new KeycloakSpringBootConfigResolver();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
存储库
package com.mytest.test.repository;
import com.mytest.test.domain.CeEncuestas;
import org.springframework.stereotype.Repository;
@Repository
public class CeEncuestasList extends GenericEncuestasList<CeEncuestas>{
public CeEncuestasList() {
super(CeEncuestas.class);
}
}
控制器:
package com.mytest.test.controller;
import com.mytest.test.domain.CeEncuestas;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@RestController
public class CanalesController {
@Autowired
private CeEncuestasList list;
@RequestMapping("/encuestas")
public List<GlobalScores> list() {
try {
List<CeEncuestas> listaEncuestas = (List<CeEncuestas>) list.getAllCanalesDiario();
}catch (Exception ex){
return new ArrayList<>();
}
return listaEncuestas;
}
}
还有我的实体管理器的通用类
package com.mytest.test.repository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.List;
@Repository
@Transactional
public abstract class GenericEncuestasList<T> {
@PersistenceContext(unitName = "persistenceUnit")
private EntityManager em;
private Class<T> entityClass;
public GenericEncuestasList(Class<T> entityClass) {
this.entityClass = entityClass;
}
public GenericEncuestasList() {
}
@Transactional
public List<?> getAllCanalesDiario() {
List<?> CeEncuestasList = new ArrayList<>();
try {
TypedQuery<?> query = em.createQuery("Select c from CeEncuestas c", entityClass);
CeEncuestasList = (List<T>) query.getResultList();
}
}catch (Exception ex){
return new ArrayList<>();
}
return CeEncuestasList;
}
}
持久性.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="persistenceUnit" transaction-type="JTA">
<jta-data-source>java:/myDataDS</jta-data-source>
<class>com.mytest.test.domain.CeEncuestas</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL94Dialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
</properties>
</persistence-unit>
</persistence>
和 myapp-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.mytest.test" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=""/>
</bean>
<jee:jndi-lookup id="dataSource" jndi-name="java:/myDataDS" />
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jtaDataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<!--<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>-->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
<tx:annotation-driven transaction-manager="emf"/>
</beans>
有什么我想念的吗?我不得不说,当我只使用 Spring 部署项目时,应用程序工作正常,问题是,我必须使我的项目成为 Spring Boot 应用程序才能在其中实现 Keycloak。
解决方案
您可以尝试覆盖 Application 类中的 #configure 方法。似乎它没有选择您 myapp-servlet.xml 中定义的配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, XADataSourceAutoConfiguration.class})
@EnableJpaRepositories("com.mytest.test.repository")
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(Application.class);
}
@Bean
public KeycloakSpringBootConfigResolver keycloakSpringBootConfigResolver(){
return new KeycloakSpringBootConfigResolver();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
如果这没有效果,我认为它仍然没有拾取 myapp-servlet.xml 然后你可以尝试用注释你的 Application 类
@ImportResource("classpath:myapp-servlet.xml") // the xml file with the beans.
public class Application extends SpringBootServletInitializer {
...
假设 myapp-servlet.xml 在 src/main/resources 文件夹中。
另见:
https ://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-traditional-deployment
https://www.baeldung.com/spring-boot-xml-豆子
推荐阅读
- php - 如何使用 PHP 将索引数组添加到某个索引上的数组?
- javascript - 反应导入和渲染另一个组件不起作用
- r - 在 R 中使用循环生成随机图和邻接矩阵
- swiftui - SwiftUI MacCatalyst 的 isMovableByWindowBackground
- python - 减少 if-else 循环
- c++ - 为什么使用 std::regex 会使编译时间增加很多?
- c# - 如何使用 ConfigurationManager 加载 dll 配置?
- python - 将 Spark Dataframe 行的值按比例分配给其他行
- ios - 当我尝试运行会提出问题的应用程序时出现错误
- python - Intellij Idea, Python Plugin - 社区版可以使用科学模式吗?