运行uber jar spring @value null

时间:2015-09-08 15:34:24

标签: spring executable uber-api

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

当我运行这个jar时,它失败并出现NullPointerException。看起来它无法在我的主类中找到@Value引用的值,我最终得到了一个N​​PE。我确实看到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。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

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

将此bean添加到配置类

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

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