在 Wildfly 中部署的 Spring Boot 应用程序“无法实例化 WebApplicationInitializer 类”

Posted

技术标签:

【中文标题】在 Wildfly 中部署的 Spring Boot 应用程序“无法实例化 WebApplicationInitializer 类”【英文标题】:Spring boot application deployed in Wildfly "Failed to instantiate WebApplicationInitializer class" 【发布时间】:2019-06-07 18:01:15 【问题描述】:

我正在使用 IntelliJ IDEA 并构建一个 Spring Boot 应用程序,即一个 REST Web 服务。从 IDE 运行应用程序时,一切似乎都正常。当我尝试在 WildFly 14 上部署它时,我收到以下错误:

"WFLYCTL0080: 失败的服务" => "jboss.deployment.unit.\".war\".undertow-deployment" => "java.lang.RuntimeException: javax.servlet.ServletException: 无法实例化 WebApplicationInitializer班级 原因:java.lang.RuntimeException: javax.servlet.ServletException: 无法实例化 WebApplicationInitializer 类 原因:javax.servlet.ServletException:无法实例化 WebApplicationInitializer 类 引起:java.lang.NoSuchMethodException: com.foo.Application.()"

我的 pom.xml:

<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.foo.<application-name></groupId>
<artifactId><application-name></artifactId>
<version>xxx</version>
<name>Application name</name>
<description>Application description
</description>

<properties>
    <start-class>com.foo.Application</start-class>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-model</artifactId>
        <version>3.5.4</version>
    </dependency>
    <dependency>
        <groupId>org.modelmapper</groupId>
        <artifactId>modelmapper</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </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-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <!-- update Hibernate dependency on Javassist to 3.23.1 for Java 11 compatibility -->
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.23.1-GA</version>
    </dependency>
    <dependency>
        <!-- update Mockito dependency for Java 11 compatibility -->
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.22.0</version><!--$NO-MVN-MAN-VER$ -->
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.12</version><!--$NO-MVN-MAN-VER$ -->
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

<packaging>war</packaging>

<build>
    <defaultGoal>install</defaultGoal>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <!--<configuration>
                <executable>true</executable>
                <skipTests>true</skipTests>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>-->
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

我的 com.foo.Application 类:

package com.foo;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;

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

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@Configuration
@EnableJpaRepositories("com.foo.repositories")
@EntityScan("com.foo.entities")
@EnableTransactionManagement
@ComponentScan( "com.foo.services", "com.foo.controllers" )
@PropertySource("classpath:application.properties")
public class Application extends SpringBootServletInitializer 
    private final Logger logger1 = LoggerFactory.getLogger(Application.class);

    @Autowired
    public Application(Environment env) 
        this.env = env;
    

    public static void main(String[] args) 
        Logger log = LoggerFactory.getLogger(Application.class);

        SpringApplication.run(Application.class, args);
        log.trace("Application started");
    

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) 
        return application.sources(Application.class);
    

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) 
        return args -> 

            logger1.trace("Let's inspect the beans provided by Spring Boot:");
            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) 
                logger1.trace(beanName);
            
        ;
    

    // Database initialization is organized according to the tutorial in https://www.baeldung.com/spring-jpa-test-in-memory-database
    private final Environment env;

    @Bean
    public DataSource dataSource() 
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(Objects.requireNonNull(env.getProperty("jdbc.driverClassName")));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));

        return dataSource;
    

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() 
        final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("com.foo.entities");
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        em.setJpaProperties(additionalProperties());
        return em;
    

    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) 
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    

    Properties additionalProperties() 
        final Properties hibernateProperties = new Properties();

        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        /*hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
        hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));*/

        return hibernateProperties;
    

    @Bean
    public ModelMapper modelMapper() 
        ModelMapper mm = new ModelMapper();
        mm.addConverter(new InteractionConverter());
        return mm;
    

    public static String getVersion() throws IOException, XmlPullParserException 
        MavenXpp3Reader reader = new MavenXpp3Reader();
        String version;
        if ((new File("pom.xml")).exists()) 
            try (FileReader pomFileReader = new FileReader("pom.xml")) 
                Model model = reader.read(pomFileReader);
                version = model.getVersion();
            

         else 
            try (InputStream stream = Application.class.getResourceAsStream(
                    "/META-INF/maven/com.foo.application-name/application-name/pom.xml")) 
                InputStreamReader pomFileReader = new InputStreamReader(stream);
                Model model = reader.read(pomFileReader);
                version = model.getVersion();
            
        

        return version;
    

    public static String getDescription() throws IOException, XmlPullParserException 
        MavenXpp3Reader reader = new MavenXpp3Reader();
        String description;
        if ((new File("pom.xml")).exists()) 
            try (FileReader pomFileReader = new FileReader("pom.xml")) 
                Model model = reader.read(pomFileReader);
                description = model.getDescription();
            
         else 
            try (InputStream stream = Application.class.getResourceAsStream(
                    "/META-INF/maven/com.foo.application-name/application-name/pom.xml")) 
                InputStreamReader pomFileReader = new InputStreamReader(stream);
                Model model = reader.read(pomFileReader);
                description = model.getDescription();
            
        

        return description;
    


如果我做对了,spring 应用程序入口点是不可见的,但我不明白为什么。我的 pom.xml 或 Application 类有问题吗?

【问题讨论】:

【参考方案1】:

跟踪source codes,发现它基本上是使用下面的代码来创建SpringBootServletInitializer的实例:

Constructor ctor = FooInitialializer.class.getDeclaredConstructor();
ctor.newInstance();

这意味着你的SpringBootServletInitializer 应该有一个无参数的构造函数。所以尝试添加一个:

public class Application extends SpringBootServletInitializer 

     Application()

【讨论】:

非常感谢您的回答。确实是这个原因。实际上,我有一个空的构造函数,但更改了它,因为 IntellJ IDEA 给了我一个警告,说 Environment env 变量“不推荐字段注入”,因此我将它添加到导致问题的构造函数中。删除我的构造函数更正了错误。但是,我的 pom.xml 似乎也有其他问题。

以上是关于在 Wildfly 中部署的 Spring Boot 应用程序“无法实例化 WebApplicationInitializer 类”的主要内容,如果未能解决你的问题,请参考以下文章

在 WildFly 8.0.0.Beta 1 上部署 spring 应用程序错误

将 Spring Boot 部署到 Wildfly 10

Spring Boot 2 重新部署到 Wildfly 10 后无法刷新 JMS 连接

未能将 Spring Boot 应用程序部署到 WildFly

从 Wildfly 10 中排除所有模块

在“更新服务器的部署扫描程序:WildFly 23”期间发生内部错误