IDEA 编译打包执行jar包报错

解决IDEA中Spring Boot项目打包成Jar后无法运行的问题,通过修改pom.xml配置实现正确打包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IDEA 编译打包执行jar包报错

在IDEA运行项目没有问题,打包成 jar 包运行出错
错误信息:

F:\MyProject\DIYC\diyc_register\target>java -jar diyc_register-1.0.0.1-jar-with-dependencies.jar

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

2019-11-20 09:45:25.241  INFO 23028 --- [           main] com.dingfeng.EurekaServerApplication     : Starting EurekaServ
erApplication on PC-20161218SQLW with PID 23028 (F:\MyProject\DIYC\diyc_register\target\diyc_register-1.0.0.1-jar-with-d
ependencies.jar started by Administrator in F:\MyProject\DIYC\diyc_register\target)
2019-11-20 09:45:25.244  INFO 23028 --- [           main] com.dingfeng.EurekaServerApplication     : No active profile s
et, falling back to default profiles: default
2019-11-20 09:45:25.280  INFO 23028 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.spri
ngframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@20d525: startup date [Wed Nov 20
 09:45:25 CST 2019]; root of context hierarchy
2019-11-20 09:45:25.374 ERROR 23028 --- [           main] o.s.boot.SpringApplication               : Application run fai
led

java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a
 custom packaging, make sure that file is correct.
        at org.springframework.util.Assert.notEmpty(Assert.java:450) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:n
a]
        at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.getCandidateConfigurations(AutoConfigu
rationImportSelector.java:160) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.selectImports(AutoConfigurationImportS
elector.java:96) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector$AutoConfigurationGroup.process(AutoCon
figurationImportSelector.java:386) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGrouping.getImports(Con
figurationClassParser.java:828) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationC
lassParser.java:563) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:188) ~[di
yc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(Configura
tionClassPostProcessor.java:316) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(Conf
igurationClassPostProcessor.java:233) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcess
ors(PostProcessorRegistrationDelegate.java:271) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostPro
cessorRegistrationDelegate.java:91) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplic
ationContext.java:692) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:530) ~
[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerAppli
cationContext.java:140) ~[diyc_register-1.0.0.1-jar-with-dependencies.jar:na]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [diyc_register-1.0.0.1-jar-wit
h-dependencies.jar:na]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [diyc_register-1.0.0.1-
jar-with-dependencies.jar:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [diyc_register-1.0.0.1-jar-with-de
pendencies.jar:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242) [diyc_register-1.0.0.1-jar-with-d
ependencies.jar:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230) [diyc_register-1.0.0.1-jar-with-d
ependencies.jar:na]
        at com.dingfeng.EurekaServerApplication.main(EurekaServerApplication.java:12) [diyc_register-1.0.0.1-jar-with-de
pendencies.jar:na]

2019-11-20 09:45:25.413  INFO 23028 --- [           main] ConfigServletWebServerApplicationContext : Closing org.springf
ramework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@20d525: startup date [Wed Nov 20 09
:45:25 CST 2019]; root of context hierarchy

F:\MyProject\DIYC\diyc_register\target>

解决方案:
修改 pom.xml

<!-- 编译插件 -->
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <fork>true</fork>
        <!--suppress UnresolvedMavenProperty -->
        <mainClass>${start-class}</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-5</version>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.dingfeng.EurekaServerApplication</mainClass>
            </manifest>
        </archive>
    </configuration>
    <executions>
        <execution>
            <id>assemble-all</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

执行命令:

mvn clean package -Dmaven.test.skip=ture  //执行打包并忽略测试文档编译

最后会在 target 目录下生成 三个文件:
XXX-1.0.0.1.jar
XXX-1.0.0.1.jar.original
XXX-1.0.0.1-jar-with-dependencies.jar
只要执行 java -jar XXX-1.0.0.1.jar 就可以了

参考:http://www.it1352.com/907745.html

<think>我们正在解决用户在使用IntelliJIDEA打包JAR文件时遇到的'UnsupportedEncodingException'错误。这个错误通常与字符编码问题有关,特别是在处理字符串和字节转换时没有指定正确的编码方式。根据引用[3]中的描述,一个类似的问题是由于在调用`getBytes()`方法时没有指定字符编码,导致在不同环境下(如Tomcat服务器和独立main方法测试)出现不一致的加密结果,并可能抛出`UnsupportedEncodingException`。因此,解决方案的核心是确保在代码中指定字符编码,通常使用UTF-8。以下是解决步骤:1.**检查代码中字节转换的地方**:在打包JAR时出现`UnsupportedEncodingException`,很可能是代码中某处使用了`String.getBytes()`或`newString(byte[])`等没有指定编码的方法。当系统默认编码与期望的编码不一致时,就会抛出此异常。2. **修改代码指定编码**:将代码中所有使用`getBytes()`的地方改为`getBytes("UTF-8")`,将`newString(byte[])`改为`newString(byte[],"UTF-8")`。这样就能确保使用统一的编码方式。例如,在引用[3]中提到的问题就是通过将`inbuf.getBytes()`改为`inbuf.getBytes("utf-8")`解决的。3.**处理异常**:确保在调用这些方法时捕获`UnsupportedEncodingException`异常。虽然UTF-8是标准编码,通常都支持,但为了安全起见,可以捕获该异常并做适当处理(如使用默认编码并记录警告)。4.**设置项目编码**:在IntelliJIDEA中,确保整个项目的文件编码设置为UTF-8。这样可以避免源文件本身的编码问题。设置方法:File-> Settings-> Editor-> FileEncodings,将GlobalEncoding、Project Encoding和Defaultencoding forproperties files都设置为UTF-8,并勾选“Transparentnative-to-asciiconversion”for propertiesfiles。5. **构建配置**:检查构建配置(如Maven或Gradle)中是否指定了编码。例如,在Maven的pom.xml中,可以配置编译器插件使用UTF-8:```xml<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>```6. **运行配置**:如果错误发生在运行JAR时,检查运行配置中的编码设置。在IntelliJIDEA的运行配置中,可以添加环境变量`JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8`来确保运行时使用UTF-8编码。7. **检查外部系统属性**:如果问题仍然存在,检查运行JAR的环境是否支持UTF-8编码。可以通过在代码中打印系统属性`file.encoding`来确认:```javaSystem.out.println(System.getProperty("file.encoding"));```8.**使用标准方式设置编码**:在启动JAR时,可以通过命令行参数指定编码:```java-Dfile.encoding=UTF-8-jaryourjar.jar```9. **处理资源文件**:如果错误发生在读取资源文件(如配置文件)时,确保使用指定编码读取。例如,使用`InputStreamReader`时指定编码:```javanew InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);```10.**依赖库问题**:如果错误是由第三方库引起的,考虑升级该库到最新版本,或者检查其文档看是否有指定编码的配置。通过以上步骤,应该能够解决`UnsupportedEncodingException`问题。核心在于统一使用UTF-8编码,并在所有需要指定编码的地方显式指定。为了帮助用户更好地理解和避免类似问题,以下是相关注意事项: -**避免使用默认编码**:在不同的操作系统和运行环境中,默认编码可能不同(如Windows可能是GBK,Linux可能是UTF-8)。因此,显式指定编码是保证一致性的关键。- **使用常量**:在Java中,推荐使用`StandardCharsets.UTF_8`常量来避免拼写错误(如"UTF-8"写成"utf8"等)。例如,修改代码片段:```java//错误写法byte[]bytes =someString.getBytes();//正确写法byte[] bytes= someString.getBytes(StandardCharsets.UTF_8);```或者:```java//错误写法Stringstr =new String(bytes);//正确写法Stringstr =new String(bytes,StandardCharsets.UTF_8);```这样既避免了异常,也保证了编码的一致性。如果用户按照上述步骤修改后仍然遇到问题,请检查是否有其他地方隐式使用了系统默认编码。最后,根据用户的问题,生成相关问题: §§相关问题§§1.如何在IntelliJIDEA中统一设置项目编码? 2.如何解决Java程序在不同环境下的编码不一致问题?3.在Java中处理字符串和字节转换时有哪些最佳实践? 4.如何配置Maven或Gradle构建工具使用UTF-8编码? 5.如何设置JVM的默认字符编码?</think>### IntelliJ IDEA 打包 JAR 出现 UnsupportedEncodingException 解决方案 `UnsupportedEncodingException` 通常由字符编码问题引起,尤其在处理字符串与字节转换时未明确指定编码导致。以下是系统化解决方案: --- #### 1. **检查代码中编码相关操作** 核心问题:代码中使用了 `getBytes()` 或 `new String(byte[])` 等未指定编码的方法。 **解决方案**: - 显式指定 UTF-8 编码(推荐): ```java // 错误写法:byte[] data = str.getBytes(); byte[] data = str.getBytes(StandardCharsets.UTF_8); // ✅ 显式指定编码 // 错误写法:String result = new String(bytes); String result = new String(bytes, StandardCharsets.UTF_8); // ✅ ``` - 若需兼容旧版 Java(低于 JDK 7): ```java byte[] data = str.getBytes("UTF-8"); // 捕获 UnsupportedEncodingException ``` > **原因**:未指定编码时,JVM 会使用系统默认编码(如 Windows 的 GBK),与部署环境冲突时即报错[^3]。 --- #### 2. **统一项目编码设置** 在 IntelliJ IDEA 中全局配置 UTF-8: - **步骤**: 1. `File` → `Settings` → `Editor` → `File Encodings` 2. 设置以下三项为 **UTF-8**: - **Global Encoding** - **Project Encoding** - **Default encoding for properties files** 3. 勾选 `Transparent native-to-ascii conversion`(针对 properties 文件) - **效果**:确保源码、资源文件编译时统一使用 UTF-8[^1]。 --- #### 3. **构建工具配置编码** **Maven 项目**:在 `pom.xml` 中添加: ```xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> ``` **Gradle 项目**:在 `build.gradle` 中添加: ```groovy tasks.withType(JavaCompile) { options.encoding = "UTF-8" } ``` --- #### 4. **运行时指定 JVM 编码** 在 JAR 启动命令中强制 UTF-8 编码: ```bash java -Dfile.encoding=UTF-8 -jar your_app.jar ``` --- #### 5. **检查依赖库的编码行为** - 若第三方库(如加密工具)内部未指定编码,需升级或替换库版本。 - 参考引用[^3]案例:MD5 工具类因省略 `getBytes("UTF-8")` 导致跨环境异常。 --- #### 6. **验证资源文件读取** 读取配置文件时显式指定编码: ```java // 错误示例:new FileReader("config.properties") try (BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream("config.properties"), StandardCharsets.UTF_8))) { // ✅ // 读取内容 } ``` --- ### 总结流程 ```mermaid graph TD A[出现 UnsupportedEncodingException] --> B[检查代码中的 getBytes/new String] B --> C{是否显式指定 UTF-8} C -->|否| D[修改代码添加 StandardCharsets.UTF_8] C -->|是| E[检查项目编码设置] E --> F[IDEA 中配置全局 UTF-8] F --> G[构建工具配置 UTF-8] G --> H[运行时添加 -Dfile.encoding=UTF-8] H --> I[问题解决] ``` > **关键点**:跨环境部署时,**始终显式指定编码**(UTF-8)可避免 90% 的编码异常[^3][^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值