where I should place log4j.properties file to enable debug logging in smslib,when it is added through maven dependencies? - maven

I'm doing some java maven project based on thucydides-jbehave-archetype.
Smslib dependency is added through maven:
<dependency>
<groupId>org.smslib</groupId>
<artifactId>smslib</artifactId>
<version>dev-SNAPSHOT</version>
</dependency>
...
<repositories>
<repository>
<id>smslib-snapshots</id>
<name>SMSLib Repository</name>
<url>http://smslib.org/maven2/snapshots/</url>
</repository>
</repositories>
Among the pure web tests I plan to do some sms sending/receiving; sms code is placed in src/main/java/projectname/gsm package (for instance, page objects are placed in src/main/java/projectname/pages, steps are placed in src/test/java/projectname.jbehave/). I'd like to enable debug messages for smslib, but not for thucydides. However, there was no location where log4j.properties worked for smslib, and there was one location, that resulted in appearing debug messages for thucydides.

You can dump your log4j.properties file in src/main/resources.
To control the log level, just create an appropriate Log4j configuration file.
...
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.foo=WARN
...
For more details, please have a look at the Log4j manual.

Can your question be rephrased as:
How do I set two different log levels using properties files for log4j - using two separate files for two classes in different packages?
If this is the case, rimero's answer is a start. But instead of dropping the properties files in src/main/sources, you need to drop each file (defining a different log level) in a directory structure reflecting the package name (for example src/main/projectname/page). Then, you can load each properties file separately using
PropertyConfigurator.configure(URL configURL)
There are a couple of ways to get the url of your properties files, see for example:
How to configure log4j with a properties file
Here is a full example:
public class TestPropertiesFile {
private static final String PREFIX = "projectname/pages";
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger
.getLogger("projectname.page.SomeClass");
private static String PROPERTIES_PATH;
static {
PROPERTIES_PATH = Thread.currentThread().getContextClassLoader()
.getResource(PREFIX + "/log4j.properties").getPath();
org.apache.log4j.PropertyConfigurator.configure(PROPERTIES_PATH);
}
public static void test() {
LOGGER.info("Logging from: " + PROPERTIES_PATH);
}
}

Related

Activate profile while submitting Apache storm topology of a maven project (Without recompiling)

I have to activate the profile while submitting the jar to storm like we do for a spring/boot project. like below
java -jar project-xyz.jar --spring.profiles.active=dev.
It is a maven project with multiple sub modules. we have the resources structured
Anything that is common to all the profiles will go in the root directory of resources, and anything that is specific to a profile (like DB connections) will go in that particular profile directory.
The root directory file will have the place holders for profile specific properties and will be replaced by the actual properties defined in profile directory.
Ex: ${mysql.host} will be resolved to localhost when local profile is active.
This final file will be placed in the classpath when we build the jar using
mvn clean install -P{profile}
And then the topology is submitted to storm like the following.
storm jar project-xyz.jar path.to.class.containing.main.method
The final properties file generated by maven will be read by a property reader, stored and served whenever requested.
private static final Map<String, Properties> properties = new HashMap<>();
public static String getProperty( String file, String key )
{
try {
if ( !properties.containsKey( file ) ) {
synchronized ( properties ) {
if ( !properties.containsKey( file ) ) {
loadProps( file );
}
}
}
return properties.get( file ).getProperty( key );
} catch ( IOException e ) {
throw new PropertyException( "There was a problem getting " + key + " from " + file + ".properties", e );
}
}
private static void loadProps( String file ) throws IOException
{
InputStream inputStream = PropertyFileHandler.class.getClassLoader().getResourceAsStream( file + ".properties" );
if ( inputStream == null ) {
throw new FileNotFoundException( "Property file " + file + ".properties not found" );
}
Properties prop = new Properties();
prop.load( inputStream );
properties.put( file, prop );
}
I've already gone through this question and its different in a way that I use maven and I have to activate the profile instead of providing specific property.
So, is there a way I can activate the profile while submitting the jar to storm somewhat like the following?
storm jar project-xyz.jar --profiles.active=dev
If not, what can I do to achieve this without re-compiling the source? Does converting it to a spring boot project help?
You won't be able to do this as long as you're using Maven to generate a jar containing a single properties file. That jar can only be used in the environment you generated it for.
Instead, you could include all the possible properties files in the jar, and decide which one to read based on a system or environment property.
A better option is probably that you generate the property files separately to the jar, and then put the jar plus property file into Storm. You can pass the property file path to your Storm submission code as a command line argument to your main method. You would then read the properties into memory, and pass them to your bolts/spouts. You need to do this loading eagerly (i.e. read the entire properties at topology submission time, rather than when you need a specific property), so your lazy loading configuration code should be discarded.
You might want something like Flux for convenience:
To enable property filtering, use the --filter command line option and
specify a .properties file. For example, if you invoked flux like so:
storm jar myTopology-0.1.0-SNAPSHOT.jar org.apache.storm.flux.Flux
--local my_config.yaml --filter dev.properties
With the following dev.properties file:
kafka.zookeeper.hosts: localhost:2181
You would then be able to reference those properties by key in your
.yaml file using ${} syntax:
- id: "zkHosts"
className: "org.apache.storm.kafka.ZkHosts"
constructorArgs:
- "${kafka.zookeeper.hosts}"
See the documentation at https://storm.apache.org/releases/2.1.0/flux.html.

Spring boot on Tomcat with external configuration

I can't find an answer to this question on stackoverflow hence im asking here so I could get some ideas.
I have a Spring Boot application that I have deployed as a war package on Tomcat 8. I followed this guide Create a deployable war file which seems to work just fine.
However the issue I am currently having is being able to externalize the configuration so I can manage the configuration as puppet templates.
In the project what I have is,
src/main/resources
-- config/application.yml
-- config/application.dev.yml
-- config/application.prod.yml
-- logback-spring.yml
So how can I possibly load config/application.dev.yml and config/application.prod.yml externally and still keep config/application.yml ? (contains default properties including spring.application.name)
I have read that the configuration is load in this order,
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
Hence I tried to load the configuration files from /opt/apache-tomcat/lib to no avail.
What worked so far
Loading via export CATALINA_OPTS="-Dspring.config.location=/opt/apache-tomcat/lib/application.dev.yml"
however what I would like to know is,
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
And is there a better method to achieve this ?
You are correct about load order. According to Spring boot documentation
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).
[Note]
You can also use YAML ('.yml') files as an alternative to '.properties'.
This means that if you place your application.yml file to /opt/apache-tomcat/lib or /opt/apache-tomcat/lib/config it will get loaded.
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
However, if you place application.dev.yml to that path, it will not be loaded because application.dev.yml is not filename Spring is looking for. If you want Spring to read that file as well, you need to give it as option
--spring.config.name=application.dev or -Dspring.config.name=application.dev.
But I do not suggest this method.
And is there a better method to achieve this ?
Yes. Use Spring profile-specific properties. You can rename your files from application.dev.yml to application-dev.yml, and give -Dspring.profiles.active=dev option. Spring will read both application-dev.yml and application.yml files, and profile specific configuration will overwrite default configuration.
I would suggest adding -Dspring.profiles.active=dev (or prod) to CATALINA_OPTS on each corresponding server/tomcat instance.
I have finally simplified solution for reading custom properties from external location i.e outside of the spring boot project. Please refer to below steps.
Note: This Solution created and executed windows.Few commands and folders naming convention may vary if you are deploying application on other operating system like Linux..etc.
1. Create a folder in suitable drive.
eg: D:/boot-ext-config
2. Create a .properties file in above created folder with relevant property key/values and name it as you wish.I created dev.properties for testing purpose.
eg :D:/boot-ext-config/dev.properties
sample values:
dev.hostname=www.example.com
3. Create a java class in your application as below
------------------------------------------------------
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
#PropertySource("classpath:dev.properties")
#ConfigurationProperties("dev")
public class ConfigProperties {
private String hostname;
//setters and getters
}
--------------------------------------------
4. Add #EnableConfigurationProperties(ConfigProperties.class) to SpringBootApplication as below
--------------------------------------------
#SpringBootApplication
#EnableConfigurationProperties(ConfigProperties.class)
public class RestClientApplication {
public static void main(String[] args) {
SpringApplication.run(RestClientApplication.class, args);
}
}
---------------------------------------------------------
5. In Controller classes we can inject the instance using #Autowired and fetch properties
#Autowired
private ConfigProperties configProperties;
and access properties using getter method
System.out.println("**********hostName******+configProperties.getHostName());
Build your spring boot maven project and run the below command to start application.
-> set SPRING_CONFIG_LOCATION=<path to your properties file>
->java -jar app-name.jar

Loading a file as a string content in a Spring service contained in a JAR built with Maven

I am using Spring with Maven and I would like to load a file contained in the maven folder src/main/resources inside a spring service annotated with #Service contained in a JAR file (used by another WAR file as a Maven dependency). This does not seem to work for many different reasons (read: for many different exceptions according to many different attempts).
I know that Maven, when building, puts the stuff in src/main/resources at the root of the JAR file. I've opened the JAR file and I've verified that.
I would prefer a File object (something I can use with utility libraries like Apache Commons IO), but also "something" else that's working is fine.
I would prefere going for stuff within the Java class annotated with #Service (i.e. no application context XML file, with stuff inside that I recall within the service etc.)
The file contains stuff that I eventually use as a List<String> where every item is a line in the original file. I need to keep this file as it is, I can not use a database or another solution different than a file.
This is not a .properties file and is not intended to be.
The following are the not working attempts (throwing NullPointerException, FileNotFoundException, IllegalArgumentException: URI is not hierarchical and so on...).
Among the attempts I have tried also adding/removing the prefix src/main/resources while trying to figure out what was wrong, but then I figured out that Maven puts all the stuff at the root of the JAR file as stated before.
#Value("classpath:src/main/resources/myFile.txt")
private Resource myFileResource;
private File myFile =
new File(this.getClass().getResource("/myFile.txt").toURI());
private File myFile =
new FileSystemResource("src/main/resources/myFile.txt").getFile();
private BufferedReader bufferedReaderMyFile =
new BufferedReader(
new InputStreamReader(getClass().getResourceAsStream("myFile.txt")));
What's wrong with what I am doing?
File inside jar file is no longer a File, so treat it as Resource and read it via Stream
InputStream inputStream = this.getClass().getResourceAsStream("/myFile.txt");
assumming you have actually packed that myFile.txt inside jar file and it is available at the root of JAR file

Maven Jaxb Generate Fails When Compiling A Module That Depends On Multiple Modules

I have an Eclipse Maven project consisting of multiple modules, some of which contain Xml schemas that I want to generate classes for (using Jaxb). My project layout is as follows:
schemas\core (pom)
schemas\core\types (jar)
schemas\vehicle (pom)
schemas\vehicle\automobile (jar)
schemas\vehicle\civic (jar)
The projects that contain schemas are:
schemas\core\types (xsd\types.xsd)
schemas\vehicle\automobile (xsd\automobile.xsd)
schemas\vehicle\civic (xsd\civic.xsd)
Some of the modules contain schemas that import schemas from other modules:
automobile.xsd imports types.xsd
civic.xsd imports types.xsd, automobile.xsd
Since the schemas are located in different projects I use a classpath catalog resolver along with catalog files to resolve the location of the schemas.
The automobile project depends on schemas in the types project. Here is the entry in its catalog file (catalog.xml):
<rewriteSystem systemIdStartString="http://schemas/core/types/" rewritePrefix="classpath:xsd/" />
Note the use of classpath:xsd/ to tell the catalog resolver to find the schemas on the classpath.
I also use episodes to prevent the classes in types from being re-generated inside the automobile project. Here is a snippit from my pom.xml:
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.8.3</version>
<configuration>
<episodes>
<episode>
<groupId>schemas.core</groupId>
<artifactId>types</artifactId>
<version>1.0-SNAPSHOT</version>
</episode>
<episodes>
<catalog>src/main/resources/catalog.xml</catalog>
<catalogResolver>org.jvnet.jaxb2.maven2.resolver.tools.ClasspathCatalogResolver</catalogResolver>
<extension>true</extension>
....
When I run mvn clean install on automobile project everything works file. The schema types.xsd is resolved on the classpath and the classes are ultimately generated.
Where I run into problems is trying to compile the project civic.
The civic project depends on both types.xsd and automobile.xsd. I use a catalog file (catalog.xml) to define the location of the schemas:
<rewriteSystem systemIdStartString="http://schemas/core/types/" rewritePrefix="classpath:xsd/" />
<rewriteSystem systemIdStartString="http://schemas/vehicle/automobile/" rewritePrefix="classpath:xsd/" />
I use episodes to prevent re-generation of the classes. Here is a snippit from the pom.xml for civic:
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.8.3</version>
<configuration>
<episodes>
<episode>
<groupId>schemas.core</groupId>
<artifactId>types</artifactId>
<version>1.0-SNAPSHOT</version>
</episode>
<episode>
<groupId>schemas.vehicle</groupId>
<artifactId>automobile</artifactId>
<version>1.0-SNAPSHOT</version>
</episode>
</episodes>
<catalog>src/main/resources/catalog.xml</catalog>
<catalogResolver>org.jvnet.jaxb2.maven2.resolver.tools.ClasspathCatalogResolver</catalogResolver>
<extension>true</extension>
...
When I try to run mvn clean install on the civic project I run into problems. It complains about not being able to resolve the public/system ids. Here are some of the error messages I get:
Could not resolve publicId [null], systemId [jar:file:/_m2repository/schemas/vehicle/automobile/1.0-SNAPSHOT/automobile-1.0-SNAPSHOT.jar!http://schemas/core/types/types.xsd]
[ERROR] Error while parsing schema(s).Location [].
com.sun.istack.SAXParseException2;
IOException thrown when processing "jar:file:/_m2repository/schemas/vehicle/automobile/1.0-SNAPSHOT/automobile-1.0-SNAPSHOT.jar!http://schemas/core/types/types.xsd".
Exception: java.net.MalformedURLException: no !/ in spec.
....
For some reason it cannot find types.xsd when trying to parse the jar file from the automobile project.
Does anyone know why this might be happening?
Thank you.
Note - I was experimenting around with tying to get things to work and I did find one way. If I remove the episodes from the pom.xml file I no longer get the error, however, the project civic ends up with all the types from the dependent modules (which is something I am tying to avoid by using the episodes).
If you want to see the full catalog.xml and pom.xml files for each project please see the following links:
types: http://pastebin.com/Uym3DY6X
automobile: http://pastebin.com/VQM4MPuW
civic: http://pastebin.com/eGSVGwmE
Author of the maven-jaxb2-plugin here.
I have just released the 0.10.0 version of the maven-jaxb2-plugin. This release fixes the MAVEN_JAXB2_PLUGIN-82 issue which is related to the reported problems.
This was actually NOT a bug in the maven-jaxb2-plugin, but an issue (or, better to say a few issues) in the XJC itself:
https://java.net/jira/browse/JAXB-1044
https://java.net/jira/browse/JAXB-1045
https://java.net/jira/browse/JAXB-1046
These issues cause problems when catalog and binding files are used together. This was also the reason why the Maven artifact resoltion did not work correctly in certain cases.
In the 0.10.0 release, I have implemented workarounds for JAXB-1044 and JAXB-1045. I will try to get my patches to the XJC via pull requests, but you know, I'm not sure, when/if Oracle guys will accept my PRs.
In the maven-jaxb2-plugin I've now implemented quite reliable workarounds. See this test project here:
https://github.com/highsource/maven-jaxb2-plugin/tree/master/tests/MAVEN_JAXB2_PLUGIN-82
This does exactly what you want: resolves schema via catalog AND Maven resolver to the resource from another artifact. Basically, this rewriting:
REWRITE_SYSTEM "http://www.ab.org" "maven:org.jvnet.jaxb2.maven2:maven-jaxb2-plugin-tests-MAVEN_JAXB2_PLUGIN-82-a:jar::!"
now works fine.
In case of problems do mvn -X and check the output, you'll also see the statements of the catalog resolver in the log. This might give you hints, what does not work.
Here's another project which uses schemas, bindings and the catalog itself from one central artifact:
https://github.com/highsource/w3c-schemas
Snippets from the POM:
<schemas>
<schema>
<url>http://www.w3.org/1999/xlink.xsd</url>
</schema>
</schemas>
<schemaIncludes/>
<bindings>
<binding>
<dependencyResource>
<groupId>${project.groupId}</groupId>
<artifactId>w3c-schemas</artifactId>
<resource>globalBindings.xjb</resource>
<version>${project.version}</version>
</dependencyResource>
</binding>
</bindings>
<catalogs>
<catalog>
<dependencyResource>
<groupId>${project.groupId}</groupId>
<artifactId>w3c-schemas</artifactId>
<resource>catalog.cat</resource>
<version>${project.version}</version>
</dependencyResource>
</catalog>
</catalogs>
Catalog:
REWRITE_SYSTEM "http://www.w3.org" "maven:org.hisrc.w3c:w3c-schemas:jar::!/w3c"
Binding:
<jaxb:bindings schemaLocation="http://www.w3.org/1999/xlink.xsd" node="/xs:schema">
<jaxb:schemaBindings>
<jaxb:package name="org.hisrc.w3c.xlink.v_1_0"/>
</jaxb:schemaBindings>
</jaxb:bindings>
So how all of this works:
Schemas as well as the catalog and global bindings are stored in the central artifact w3c-schemas.
The project wants to compile the URL http://www.w3.org/1999/xlink.xsd.
The catalog rewrites this URL into the systemId maven:org.hisrc.w3c:w3c-schemas:jar::!/w3c/1999/xlink.xsd. (There's a /w3c/1999/xlink.xsd resource in the w3c-schemas jar).
This systemId is then resolved my the Maven catalog resolver (delivered my the maven-jaxb2-plugin) into the "real" URL which will be some jar:... URL pointing to the resource within the w3c-schemas artifact JAR in the local repository.
So the schema is not downloaded from the Internet but taken from the local resource.
The workaround keep the "original" systemIds, therefor you can customize the schema using its original URL. (The resolved systemId won't be convenient.)
The catalog file and the global bindings file will be the same for all the individual projects, so they're also put into the central artifact and referenced there using the dependencyResource.
I have the same problem. Schema C imports B and A, B imports A. Generating sources for A, works, B is also fine and for C a MalformedUrlException pops up.
I'm still investigating the error but a workaround is to use the systemIdSuffix (Oasis spec 1.1) to match the systemId and rewrite it. You need to do the following:
Remove the 'catalogResolver' element from the plugin configuration in the poms.
Replace the content of the catalog file for the 'automobile' project with the following:
<systemSuffix systemIdSuffix="types.xsd" uri="maven:schemas.core:types!/types.xsd"/>
Replace the content of the catalog file for the 'civic' project with the following:
<systemSuffix systemIdSuffix="types.xsd" uri="maven:schemas.core:types!/types.xsd"/>
<systemSuffix systemIdSuffix="automobile.xsd" uri="maven:schemas.vehicle:automobile!/automobile.xsd"/>
Let me know if this works for you.
I faced similar problems. I used the sample projects found here.
I modified these projects in 2 ways:
1) Have an A project with 2 namespaces and a local catalog file. Have a project B depending on this, using the episode of A in B.
2) Have an A project, a B project and a C project. B relies on A and C relies on B.
In both cases I got the same exception as you. But I started to realize in situation 2 what is happening.
This is the exception:
com.sun.istack.SAXParseException2; IOException thrown when processing "jar:file:/Users/sjaak/.m2/repository/org/tst/b-working/1.0/b-working-1.0.jar!http://www.a1.org/a1/a1.xsd". Exception: java.net.MalformedURLException: no !/ in spec.
So, it tries to resolve namespace http://www.a1.org/a1/a1.xsd relative to project B when building project C. I traced the problem back to com.sun.tools.xjc.reader.internalizerAbstractReferenceFinderImpl, method startElement.
The solution I use is adapting the org.jvnet.jaxb2.maven2:maven-jaxb2-plugin. I used their MavenCatalogResolver (the default one as pointed out above) and made a small change, simply not offering the whole systemId: jar:file:/Users/sjaak/.m2/repository/org/tst/b-working/1.0/b-working-1.0.jar!http://www.a1.org/a1/a1.xsd, but in stead use a pattern that only offers the part after the exclamation mark for resolving.
Here's the code:
package org.jvnet.jaxb2.maven2.resolver.tools;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import org.jvnet.jaxb2.maven2.DependencyResource;
import org.jvnet.jaxb2.maven2.DependencyResourceResolver;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MavenCatalogResolver extends
com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver {
private final static Pattern PTRN = Pattern.compile("^jar:file:(.*).jar!(.*)$");
public static final String URI_SCHEME_MAVEN = "maven";
private final DependencyResourceResolver dependencyResourceResolver;
private final CatalogManager catalogManager;
public MavenCatalogResolver(CatalogManager catalogManager,
DependencyResourceResolver dependencyResourceResolver) {
super(catalogManager);
this.catalogManager = catalogManager;
if (dependencyResourceResolver == null) {
throw new IllegalArgumentException(
"Dependency resource resolver must not be null.");
}
this.dependencyResourceResolver = dependencyResourceResolver;
}
#Override
public String getResolvedEntity(String publicId, String systemId)
{
String result;
Matcher matcher = PTRN.matcher(systemId);
if (matcher.matches())
{
result = super.getResolvedEntity(publicId, matcher.group(2));
}
else
{
result = super.getResolvedEntity(publicId, systemId);
}
if (result == null) {
return null;
}
try {
final URI uri = new URI(result);
if (URI_SCHEME_MAVEN.equals(uri.getScheme())) {
final String schemeSpecificPart = uri.getSchemeSpecificPart();
try {
final DependencyResource dependencyResource = DependencyResource
.valueOf(schemeSpecificPart);
try {
final URL url = dependencyResourceResolver
.resolveDependencyResource(dependencyResource);
String resolved = url.toString();
return resolved;
} catch (Exception ex) {
catalogManager.debug.message(1, MessageFormat.format(
"Error resolving dependency resource [{0}].",
dependencyResource));
}
} catch (IllegalArgumentException iaex) {
catalogManager.debug.message(1, MessageFormat.format(
"Error parsing dependency descriptor [{0}].",
schemeSpecificPart));
}
return null;
} else {
return result;
}
} catch (URISyntaxException urisex) {
return result;
}
}
}
This actually fixed my problem. I'll investigate a bit more. I've got the feeling there might be some XJC arg that I could use, or perhaps the catalog XML format offers more possibilities.
Hope it helps.

maven spring test application contexts

I want to use the applicationContext.xml in my src/main/resources directory from within my test harness in src/test/java. How do I load it? I have tried:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestService {
...
}
but get a file not found error. I'm using Maven and Spring. Thanks.
Try this (note the asterisk):
#ContextConfiguration("classpath*:applicationContext.xml")
The Maven test classpath uses the files in target/test-classes. That folder contains Java classes from src/test/java and resources from src/test/resources.
The way to go is to create a test specific app context and store it under src/main/resources.
You may try to reference the file directly using file: i.e. something like file:src/main/resources/applicationContext.xml but to me this is an ugly hack.
Also, you can of course use the Maven resources plugin to copy applicationContext.xml prior to test execution.
Here's how I do it, it may or may not be the best way for you. The main thing is it works in both Eclipse and Maven:
Keep exactly one copy of each applicationContext-xxx.xml file per project. NEVER copy-and-paste them or their contents, it'll create a maintenance nightmare.
Externalize all environmental settings to properties files (e.g. database-prod.properties and database-test.properties) and place them in src/main/resources and src/test/resources respectively. Add this line to your app contexts:
<context:property-placeholder location="classpath:**/*.properties"/>
Create a superclass for all test classes and annotate it with a context configuration:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:applicationContext.xml"})
#Ignore
public class SpringEnabledTest {
// Inheritable logger
protected Logger logger = LoggerFactory.getLogger(this.getClass());
}
Add <additionalClasspathElements> to your maven-surefire-plugin configuration to make sure surefire picks up appContext and the right properties files. I've created an example here.
Add the location(s) of the app context files and src/test/resources to your Eclipse classpath so you can execute unit tests in Eclipse as well.
NEVER add src/main/resources to your Eclipse classpath, it's only a convenient place for Maven to package additional source files, it should have no bearing on Eclipse. I often leave this directory blank and create additional folders (e.g. env/DEV, env/UAT and env/PROD) outside of the src/ folder and pass a parameter to the build server and let it know from which folder it needs to copy files to src/main/resources.
Add the src folder to the classpath of your testing tool. If it's in Eclipse, I think you can do it from the project properties. You may have to change it to classpath:**/applicationContext.xml as well.

Resources