我需要几个配置文件进行部署。在Maven POM中,我定义了一个配置文件"dev"和一个属性"theHost"(作为localhost):
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault> <!-- use dev profile by default -->
</activation>
<build>
</build>
<properties>
<theHost>localhost</theHost>
</properties>
</profile>
...
我在maven ejb插件上激活了filterDeploymentDescriptor
,以便告诉它过滤(替换)ejb-jar.xml中的值:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.3</version>
<configuration>
<ejbVersion>3.1</ejbVersion>
--> <filterDeploymentDescriptor>true</filterDeploymentDescriptor>
</configuration>
</plugin
最后,在ejb-jar.xml中,我引用${theHost}
来获得@Resource属性"host"所需的配置文件特定值:
<session>
<ejb-name>MongoDao</ejb-name>
<ejb-class>com.coolcorp.MongoDao</ejb-class>
<session-type>Stateless</session-type>
<env-entry>
<env-entry-name>host</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>${theHost}</env-entry-value>
</env-entry>
...
这一切都适用于常规的Maven构建。但是,当我使用GlassFish的嵌入式企业Bean容器[EJBContainer.createEJBContainer()]运行EJB单元测试时,maven EJB插件似乎忽略了filterDeploymentDescriptor=true。EJB看到的是"${theHost}"而不是"localhost",尽管我使用相同的"dev"配置文件运行maven。
mvn.bat -Pdev test
有人知道为什么在运行单元测试时替换不起作用吗?我是否还需要为单元测试定义更多内容,以便对ejb-jar.xml进行过滤?或者,如果存在不同的概要文件,那么是一种更好的单元测试EJB的方法?
理想情况下,您可以为env条目指定一个外部"绑定"。我知道使用WebSphereApplicationServer(通过EnvEntry.Value属性)是可能的,但我不知道使用Glassfish是否可能。
作为一种解决方法,您可以声明要注入的env条目,然后在PostConstruct中检查容器是否注入了任何值(即,在部署到服务器之前不要指定env条目值)。如果仅使用JNDI,则可以使用try/catch(NameNotFoundException)执行相同的操作。
@Resource(name="host")
private String host;
@PostConstruct
public void postConstruct() {
if (host == null) {
// Not configured at deployment time.
host = System.getProperty("test.host");
}
}
基于bkail建议的解决方案:仅为单元测试设置系统属性,并在postConstruct:中发现它
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
<skip>false</skip>
<argLine>-Xmx1g -XX:MaxPermSize=128m</argLine>
<reuseForks>false</reuseForks> <!-- with reuse the EJB timer service would fail -->
<systemPropertyVariables>
<is.unittest>true</is.unittest>
</systemPropertyVariables>
</configuration>
</plugin>
然后在用@PostConstruct:注释的Java方法中
// Override values that were not substituted in ejb-jar.xml
if (Boolean.getBoolean("is.unittest")) {
host = "localhost";
port = "27017";
authenticationRequired = false;
}