分块构建maven工程

一、构建maven_parent

此工程为父工程,其他子工程均要继承该工程。在此工程pom.xml需要注意两点:1.打包方式为pom  2.一般在这里进行各类jar包的版本锁定,下面贴出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>

    <groupId>com.itheima</groupId>
    <artifactId>maven_parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--用于聚合其他maven工程-->
    <modules>
        <module>maven_pojo</module>
        <module>maven_service</module>
        <module>maven_dao</module>
        <module>maven_web</module>
    </modules>
    <packaging>pom</packaging>
    <properties>
        <spring.version>5.0.5.RELEASE</spring.version>
        <springmvc.version>5.0.5.RELEASE</springmvc.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>
    <!--锁定jar版本-->
    <dependencyManagement>
        <dependencies>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!-- springMVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${springmvc.version}</version>
            </dependency>
            <!-- spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

二、构建maven_pojo

此工程较为简单,不需要框架支持,故不需要引入相关jar包,只需在此工程创建实体类pojo即可。

三、构建maven_dao

1.引入相关依赖

此工程需要引入mybatis和spring的相关jar包,贴出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">
    <parent>
        <artifactId>maven_parent</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>maven_dao</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.itheima</groupId>
            <artifactId>maven_pojo</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- Mybatis和mybatis与spring的整合 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- MySql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <!-- druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!-- spring相关 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>

2.创建ItemMapper.xml接口

package com.itheima.ssm.dao;

import com.itheima.ssm.pojo.Item;

public interface ItemMapper {
    public Item findById(int id);
}

3.创建applicationContext-dao.xml和ItemMapper.xml映射

applicationContext-dao.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						   http://www.springframework.org/schema/beans/spring-beans.xsd
						   ">

    <!--配置数据源信息,使用druid连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssmtest"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--配置spring整合mybatis框架的SQLSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--扫描pojo包,为实体类创建别名-->
        <property name="typeAliasesPackage" value="com.itheima.ssm.pojo"/>
    </bean>

    <!--mapper扫描器,用于产生代理对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.ssm.dao"/>
    </bean>
</beans>

ItemMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.ssm.dao.ItemMapper">
    <select id="findById" parameterType="int" resultType="Item">
        select * from item where id = #{id}
    </select>
</mapper>

四、构建maven_service

1.pom.xml

在pom.xml引入maven_dao依赖,继承maven_dao的相关jar包

2.创建applicaionContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						   http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/context
						   http://www.springframework.org/schema/context/spring-context.xsd
						   http://www.springframework.org/schema/tx
						   http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--配置扫描器,扫描Service-->
    <context:component-scan base-package="com.itheima.ssm.service"/>

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--事物注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

3.创建ItemServiceImpl

@Service
@Transactional
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;

    public Item findById(int id) {
        return itemMapper.findById(id);
    }
}

五、构建maven_web

注意:创建maven_web工程,打包方式为war

1.pom.xml

在pom中引入maven_service依赖

2.创建springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						   http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/context
						   http://www.springframework.org/schema/context/spring-context.xsd
						   ">
    <!--配置扫描器,扫描Controller-->
    <context:component-scan base-package="com.itheima.ssm.controller"/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.创建web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--指定Spring配置文件位置-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
  </context-param>

  <!--配置Spring框架启动时使用的监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--配置SpringMVC的前端控制器-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

4.创建ItemController

 

创建完毕,将maven_web添加至tomcat启动即可

<think>好的,用户现在的问题是,如何在Spring Boot工程中将文件打包到Jar包中,并在代码中使用JDK 1.8读取该文件的内容。之前用户问过JDK8实现InputStream.readAllBytes的问题,现在这个问题可能也是同一个项目的延续,用户可能正在处理资源文件的读取问题,特别是在打包后环境中。 首先,需要理解Spring Boot打包后的结构。当使用Spring Boot打包成可执行Jar时,资源文件会被包含在Jar包内部,路径和文件结构与传统的文件系统不同。因此,直接使用File或FileInputStream可能无法正确访问这些资源,因为它们在Jar包内,而不是作为单独的文件存在。 接下来,用户提到使用JDK 1.8,所以需要考虑兼容性,不能使用JDK9+的特性,比如InputStream.readAllBytes()。之前的回答中已经给出了自定义的readAllBytes方法,这里可能需要再次使用该方法,或者使用其他兼容JDK8的方式读取流。 用户可能需要知道如何正确获取资源文件的InputStream。在Spring Boot中,通常使用ClassPathResource或者ResourceLoader来加载类路径下的资源。例如,通过ClassPathResource的getInputStream()方法可以获取到文件的输入流,然后读取内容。 另外,需要注意资源文件的位置。用户需要将文件放在src/main/resources目录下,这样在打包时才会被包含到类路径中。如果文件放在其他位置,可能需要调整路径或配置构建工具(如Maven或Gradle)来包含这些文件。 还有可能的错误处理,比如文件不存在时的异常处理,读取过程中的IO异常等,需要确保代码有适当的try-catch块,或者抛出合适的异常,避免程序崩溃。 此外,用户可能在读取文件时遇到路径问题,比如使用绝对路径和相对路径的区别。在Jar包内部,资源文件没有绝对路径,必须通过类加载器来访问,因此正确使用类路径资源是关键。 最后,可能需要考虑不同环境下的测试,比如在IDE中运行和打包后运行的区别,确保代码在两种情况下都能正确读取文件内容。同时,可能需要给出具体的代码示例,展示如何加载资源、读取内容,并处理异常情况。</think>--- ### 一、Spring Boot文件打包机制 1. **资源文件默认位置**: - 必须将文件放在`src/main/resources`目录下 - 推荐建立子目录(如`resources/files`)进行分类管理 2. **打包后文件位置**: ```shell # 查看Jar包内文件结构 jar tf your-application.jar | grep example.txt # 输出示例:BOOT-INF/classes/files/example.txt ``` 3. **关键限制**: - **禁止使用**`File`或`FileInputStream` - 必须通过类加载器访问资源 --- ### 二、JDK8兼容实现方案 #### 方案1:使用Spring的ClassPathResource(推荐) ```java import org.springframework.core.io.ClassPathResource; import java.io.InputStream; public class ResourceReader { public static String readFile() throws IOException { // 指定资源路径(注意:路径不以/开头) ClassPathResource resource = new ClassPathResource("files/example.txt"); try (InputStream inputStream = resource.getInputStream()) { // 使用自定义readAllBytes方法(JDK8兼容) byte[] bytes = readAllBytes(inputStream); return new String(bytes, StandardCharsets.UTF_8); } } // JDK8的readAllBytes实现(见前文) private static byte[] readAllBytes(InputStream is) throws IOException { ... } } ``` #### 方案2:直接使用类加载器 ```java public class ClassicResourceLoader { public static String loadTextFile() throws IOException { // 注意路径以/开头 try (InputStream is = getClass().getClassLoader() .getResourceAsStream("/files/example.txt")) { if (is == null) { throw new FileNotFoundException("未找到资源文件"); } byte[] bytes = readAllBytes(is); return new String(bytes, "UTF-8"); } } } ``` --- ### 三、路径匹配规则对比 | 访问方式 | 示例路径 | 是否以`/`开头 | 实际查找位置 | |-----------------------|-----------------------|-------------|-------------------------------| | `ClassPathResource` | `files/example.txt` | 否 | classpath*:files/example.txt | | `ClassLoader` | `/files/example.txt` | 是 | classpath根目录下的对应文件 | | `ResourceUtils` | `classpath:...` | 否 | 仅开发环境有效(不可用于Jar包) | --- ### 四、常见错误排查 1. **文件未找到异常**: ```java // 错误日志示例 java.io.FileNotFoundException: class path resource [files/example.txt] cannot be opened // 解决方案: // 1. 检查文件是否在resources目录下 // 2. 确认打包后文件存在于Jar包中 ``` 2. **中文乱码问题**: ```java // 错误写法 new String(bytes); // 使用平台默认编码 // 正确写法 new String(bytes, StandardCharsets.UTF_8); ``` 3. **内存溢出处理**: ```java // 大文件建议分块读取(示例:逐行处理) try (BufferedReader reader = new BufferedReader( new InputStreamReader(resource.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { processLine(line); // 自定义处理逻辑 } } ``` --- ### 五、Maven配置验证 ```xml <!-- 确保资源文件包含配置 --> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.txt</include> <include>**/*.properties</include> </includes> </resource> </resources> </build> ``` --- ### 六、扩展应用场景 1. **读取配置文件**: ```java // application.properties中定义 file.location=classpath:files/example.txt // 通过@Value注入 @Value("${file.location}") private Resource configFile; ``` 2. **读取二进制文件**: ```java public byte[] readImage() throws IOException { ClassPathResource resource = new ClassPathResource("images/logo.png"); try (InputStream is = resource.getInputStream()) { return readAllBytes(is); } } ``` 3. **多环境配置**: ```properties # application-dev.properties custom.file=classpath:env/dev/config.xml # application-prod.properties custom.file=classpath:env/prod/config.xml ``` --- ### 七、性能优化建议 1. **资源缓存机制**: ```java private static final Map<String, String> CACHE = new ConcurrentHashMap<>(); public String getCachedFile(String path) throws IOException { return CACHE.computeIfAbsent(path, p -> { try { return readFileContent(p); } catch (IOException e) { throw new UncheckedIOException(e); } }); } ``` 2. **预热加载**: ```java @PostConstruct public void preloadResources() { // 在应用启动时加载关键资源 Arrays.asList("file1", "file2").forEach(this::getCachedFile); } ``` --- 通过上述方案,可以在Spring Boot + JDK8环境下实现安全的资源文件读取,并正确处理打包后的Jar文件结构。关键点在于: 1. 使用正确的资源加载API 2. 避免直接文件系统操作 3. 正确处理字符编码 4. 注意资源释放和异常处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值