通常在项目中都会使用maven进行多模块管理,默认被依赖的模块都会以jar包形式被引用。 然而在J2EE项目中,当使用了Spring的自动扫描配置时,jar包形式的依赖class将不能被自动装配:<context:component-scan base-package="com.xxx.xxx" /> 。
例如,存在如下结构的maven多模块项目: --test-root --test-account(账户模块) --test-report(报表模块) --test-web(页面模块) test-web模块同时依赖了test-account,test-report,所有模块的包名前缀都相同,便于在test-web配置根据包名自动扫描装配bean。 默认情况下,test-account和test-report两个模块都会以jar包的形式添加到test-web/WEB-INF/lib目录下。 但是,此时一旦在test-web模块中通过自动注入bean的方式引用test-account和test-report中的组件,将会报java.lang.NullPointerException异常。 也就是说,test-account和test-report中的组件并没有被自动注入,这是因为test-account和test-report中的组件并没有被spring自动扫描到并进行装配。
而要解决这个问题,必须将被依赖模块中的组件class文件打包到test-web/WEB-INF/classes目录中,即:打包时需要将被依赖模块的class文件copy到指定位置。 通过插件maven-dependency-plugin可以解决此问题,详见:https://maven.apache.org/plugins/maven-dependency-plugin/
test-web模块pom.xml配置案例如下:
1 <build>
2 <plugins>
3 <!-- 将依赖模块的jar包文件提取出来放到指定位置 -->
4 <plugin>
5 <groupId>org.apache.maven.plugins</groupId>
6 <artifactId>maven-dependency-plugin</artifactId>
7 <executions>
8 <execution>
9 <id>unpack</id>
10 <phase>prepare-package</phase>
11 <goals>
12 <goal>unpack</goal>
13 </goals>
14 <configuration>
15 <artifactItems>
16 <artifactItem>
17 <groupId>com.test</groupId>
18 <artifactId>test-account</artifactId>
19 <version>1.0.0</version>
20 <type>jar</type>
21 <includes>**/*.class</includes>
22 <overWrite>false</overWrite>
23 <outputDirectory>${project.build.directory}/classes</outputDirectory>
24 </artifactItem>
25 <artifactItem>
26 <groupId>com.test</groupId>
27 <artifactId>test-report</artifactId>
28 <version>1.0.0</version>
29 <type>jar</type>
30 <includes>**/*.class</includes>
31 <overWrite>false</overWrite>
32 <outputDirectory>${project.build.directory}/classes</outputDirectory>
33 </artifactItem>
34 </artifactItems>
35 </configuration>
36 </execution>
37 </executions>
38 </plugin>
39 <plugins>
40 </build>