0

我需要从我的 Maven 模块(Java+Spring)及其依赖项创建一个可执行的 jar。所以我在我的 POM 中包含了 maven-shade-plugin,看起来它打包了所有需要的东西。

当我运行这个 jar 时,它会因 NullPointerException 而失败。看起来它无法在我的主类中找到 @Value 引用的值,我最终得到了一个 NPE。我确实看到 applicationContext 和属性文件在 jar 中。这可能是什么原因?

applicationContext.xml -

<context:property-placeholder location="classpath:props.properties" ignore-unresolvable="true"/>

Main.java -

@Value("${property.inside.props.file}")
private String propertyName;

pom.xml -

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.1</version>
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>shade</goal>
                </goals>
                <configuration>
                <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <manifestEntries>
                        <Main-Class>com.sloan.Main.java</Main-Class>
                    </manifestEntries>
                </transformer>
        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.handlers</resource>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.schemas</resource>
                </transformer>
            </transformers>
                 <filters>
                 <filter>
                      <artifact>*:*</artifact>
                      <excludes>
                        <exclude>META-INF/*.SF</exclude>
                        <exclude>META-INF/*.DSA</exclude>
                        <exclude>META-INF/*.RSA</exclude>
                      </excludes>
                    </filter>
                    </filters>
                </configuration>
              </execution>
            </executions>
          </plugin>

我曾尝试对程序集插件做同样的事情,但这也带来了 NPE。

4

2 回答 2

1

我找到了我缺少的东西,加载了 Spring 上下文!所以现在我的 Main.java 首先加载上下文 -

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF\\spring\\applicationContext.xml");

进行此更改并重新安装后,一切正常。

于 2015-09-10T06:16:49.267 回答
0

您缺少@Bean负责解决此注释的

将此 bean 添加到您的配置类

@Bean
public static PropertyPlaceholderConfigurer getValueResolver()
{
    return new PropertyPlaceholderConfigurer();
}

对于基于 XML 的教程,请看这里 http://www.mkyong.com/spring/spring-propertyplaceholderconfigurer-example/

于 2015-09-08T17:03:54.567 回答