Here is the structure of sample Spring application
src
main
my.example
- MyBean.java
- AppMain.java
resources
- applicationContext.xml
- some.properties
applicationContext.xml
<beans ...>
<context:property-placeholder location="classpath:some.properties"/>
<bean id="a" class="my.example.MyBean"/>
</beans>
some.properties
myprop=something
AppMain.java
public class AppMain {
public static void main(String[] args) {
var context = new ClassPathXmlApplicationContext();
context.setConfigLocations("classpath:applicationContext.xml");
context.refresh();
var bean = context.getBean("a");
println(bean); // available
ConfigurableEnvironment environment = context.getEnvironment();
String javaHome = environment.getProperty("java.home");
String myprop = environment.getProperty("myprop");
println(environment.getPropertySources());
println("javaHome is " + javaHome); // ok
println("myprop is " + myprop); // is null
}
}
Output:
my.example.MyBean#cecf639
[PropertiesPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}]
javahome is [/mypath/to/java/17.0.5-zulu]
myprop is [null]
As the output shows the property sources do not contains some.properties file, and hence myprop is null. At the same time the bean MyBean is available, which means applicationContext.xml was processed.
Why <context:property-placeholder ...> had no effect?
How to add some.properties file to the context, and get correct myprop value?
Related
I am new to spring framework and following the tutorial on tutorialspoint.com. After including every thing, while running the program it gives me following error:
Error: Unable to initialize main class com.raza.spring.MainApp
Caused by: java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
Below is my project structure:
enter image description here
Here is the code:
Class Hello:
package com.raza.spring;
public class Hello {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
}
Class MainApp:
package com.raza.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Hello obj = (Hello) context.getBean("helloWorld");
obj.getMessage();
}
}
Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.raza.spring.Hello">
<property name = "message" value = "Hello raza world !!!"/>
</bean>
</beans>
Not able to get what is wrong here. Thanks in advance.
I am trying tutorial on tutorialspoint.com and expecting an output on the console.
java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext tells that the Class you are using in your code is not accessible from your project.
In previous chapter on https://www.tutorialspoint.com/spring/spring_environment_setup.htm you probably downloaded spring library in step 4. Try adding it to your classpath: https://wiki.eclipse.org/FAQ_How_do_I_add_an_extra_library_to_my_project%27s_classpath%3F.
I highly recommend you start using maven. It allows you to add external libraries a lot easier, without having to manually download them from a git repo or a website.
Also, check the Baeldung courses. Their examples always use the latest Spring version https://www.baeldung.com/spring-tutorial
I have bean below bean in dto-mapping-v2-spring.xml which is under WEB-INF/config folder.
<alias alias="dataMapper" name="defaultDataMapper"/>
<bean id="defaultDataMapper"
class="de.hybris.platform.webservicescommons.mapping.impl.DefaultDataMapper">
<property name="fieldSetBuilder" ref="fieldSetBuilder"/>
</bean>
I trying to inject it in one of my service.I added this configuration in spring.xml under resources folder.
<alias name="defaultProductExportService" alias="ProductExportService"/>
<bean class="com.service.DefaultProductExportService" id="defaultProductExportService">
<property name="datamapper" ref="datamapper" />
</bean>
During server start it is throwing and error saying
Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataMapper' available
How I can inject bean?
Class inside extension/src/ with its bean definition inside resources/extension-spring.xml cannot access bean that's inside web/webroot/WEB-INF/, bean inside WEB-INF can only be accessed by class inside web/src/ or commonweb/src
extension
| - src/
| - resources
| | - extension-spring.xml
|
| - web
| -- src/
| -- webroot / WEB-INF / config
The answer of #Adiputera is correct but if someone still needs it:
Getting bean from any context using groovy script in hybris:
import de.hybris.platform.core.PK
import de.hybris.platform.spring.HybrisContextLoaderListener
import org.apache.commons.lang3.reflect.FieldUtils
import org.springframework.web.context.ContextLoader
import org.springframework.web.context.WebApplicationContext
STOREFRONTCONTEXT = "previewwebservices"
def f = ContextLoader.getDeclaredField("currentContextPerThread")
f.setAccessible(true)
Map<ClassLoader, WebApplicationContext> contexts = f.get(HybrisContextLoaderListener)
def appContext = contexts.find {STOREFRONTCONTEXT.equals(it.key.getContextName())}
//When the context is found, we are ready to get our beans
if (appContext ==null) println "Impossible to retrieve application context"
else {
defaultSyncService = appContext.value.getBean("synchronizationService")
}
ref:
https://www.stackextend.com/hybris/getting-bean-from-any-context-using-groovy-script-in-hybris/
or with JAVA:
public DataMapper getDataMapper() {
DataMapper dataMapper = null;
try {
String STOREFRONTCONTEXT = "commercewebservices";
Field f = ContextLoader.class.getDeclaredField("currentContextPerThread");
f.setAccessible(true);
Map<HybrisWebappLoader.HybrisWebappClassLoader, WebApplicationContext> contexts = (Map<HybrisWebappLoader.HybrisWebappClassLoader, WebApplicationContext>) f.get(HybrisContextLoaderListener.class);
Optional<HybrisWebappLoader.HybrisWebappClassLoader> appContextKey = contexts.keySet().stream().filter(key -> key.getContextName().equals(STOREFRONTCONTEXT)).findFirst();
if (appContextKey.isPresent()) {
dataMapper = contexts.get(appContextKey.get()).getBean("dataMapper", DataMapper.class);
}
} catch (IllegalAccessException | NoSuchFieldException e) {
LOG.error("Impossible to retrieve application context", e);
}
return dataMapper;
}
I'm working on writing tests for the route
The problem is all my routes contain properties that described in application.properties file e.g
from("oracleQueue:{{oracle.queue.url}}").to("my.endpoint")
It works fine but when I try to write a test - seems like this route can't find application.properties file with its properties.
The error:
java.lang.IllegalArgumentException: Property with key [oracle.queue.url] not found in properties from text: oracleQueue:{{oracle.queue.url}}
My testcase:
public class RouteTest extends CamelTestSupport {
#Override
protected RoutesBuilder createRouteBuilder() {
MyRouteBulder route = new MyRouteBulder ();
ApplicationContext appContext = new ClassPathXmlApplicationContext("camel-context.xml");
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("application.properties");
CamelContext context = new SpringCamelContext(appContext);
context.addComponent("properties", pc);
route.setContext(context);
return route;
}
#Test
public void test() throws InterruptedException {
MockEndpoint mockEndpoint = resolveMandatoryEndpoint("my.endpoint", MockEndpoint.class);
mockEndpoint.expectedMessageCount(1);
template.sendBody("oracleQueue:{{oracle.queue.url}}", "hello world");
mockEndpoint.assertIsSatisfied();
}
}
How should I set up configuration file properly?
Maybe you need an absolute path for the location.
I use this to get props
<bean
class="org.apache.camel.component.properties.PropertiesComponent"
id="properties" name="properties">
<property name="cache" value="false"/>
<property name="locations">
<list>
<value>file:${CONF}/broker.properties</value>
<value>file:${CONF}/sops/domains/properties/a92fe32d-01c9-4c00-b2c0-b17a71503bbe.properties;optional=true</value>
</list>
</property>
</bean>
I have an app that uses jars from other apps. My application which is called com_Streams_H2O_ML.java uses HazelcastInsance.
package com.escomled.machinelearning.ml;
import static com.com.machinelearning.ml.PropertiesGenerator.getProperty;
import java.io.File;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KStreamBuilder;
import org.springframework.stereotype.Repository;
import com.com.blackboard.Blackboard;
import com.com.machinelearning.ml.Escomled_Streams_H2O_ML;
import com.com.machinelearning.startmap.ContextHolder;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import hex.genmodel.easy.EasyPredictModelWrapper;
import hex.genmodel.easy.RowData;
import hex.genmodel.easy.exception.PredictException;
import hex.genmodel.easy.prediction.RegressionModelPrediction;
/**
*
*
* Creates a new Kafka Streams application for prediction of watts The
* application uses the GBM model "comPOJO" (built with H2O.ai and python
* application) to infer messages sent to Kafka topic "comInputTopic". The
* outcome of model inference is sent to Kafka topic "comOutputTopic".
*
*/
public class com_Streams_H2O_ML {
// Name of the generated H2O model
private static String modelClassName = getProperty("pojoFullName");
// Prediction Value
private static double watts = 0;
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); // match a number with optional '-' and decimal.
}
public static void main(final String[] args) throws Exception {
System.out.println(new File(".").getAbsolutePath());
// Create H2O object (see gbm_pojo_test.java)
hex.genmodel.GenModel rawModel;
rawModel = (hex.genmodel.GenModel) Class.forName(modelClassName).newInstance();
EasyPredictModelWrapper model = new EasyPredictModelWrapper(
new EasyPredictModelWrapper.Config().setModel(rawModel).setConvertUnknownCategoricalLevelsToNa(false));
HazelcastInstance instance = ((Blackboard) ContextHolder.getContext().getBean("blackboard")).getHazelcastInstance();
IMap<String, String> dimmingMap = instance.getMap("dim_board_map");
// Configure Kafka Streams Application
final String bootstrapServers = args.length > 0 ? args[0] : getProperty("bootstrapServers");
final Properties streamsConfiguration = new Properties();
// Give the Streams application a unique name. The name must be unique
// in the Kafka cluster
// against which the application is run.
streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "Escomled_Streams_ML");
// Where to find Kafka broker(s).
streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
// Specify default (de)serializers for record keys and for record
// values.
streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
streamsConfiguration.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
// For illustrative purposes we disable record caches
streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
// In the subsequent lines we define the processing topology of the
// Streams application.
final KStreamBuilder builder = new KStreamBuilder();
// Construct a `KStream` from the input topic "EscomledInputTopic", where
// message values
// represent lines of text (for the sake of this example, we ignore
// whatever may be stored
// in the message keys).
String inputTopic = getProperty("inputTopic");
final KStream<String, String> predictionInput = builder.stream(inputTopic);
// Stream Processor (in this case 'foreach' to add custom logic, i.e. apply the
// analytic model)
predictionInput.foreach((key, value) -> {
String[] values = value.split(",");
System.out.println("Key " + key);
System.out.println("Value " + value);
if (value != null && !value.equals("") && isNumeric(value)) {
RowData row = new RowData();
row.put("Board Number", key);
row.put("Dimming", value);
RegressionModelPrediction p = null;
try {
p = model.predictRegression(row);
watts = p.value;
System.out.println("Prediction for " + key + "/" + value + "% :" + watts + "W");
} catch (PredictException e) {
e.printStackTrace();
}
dimmingMap.remove(key);
} else {
System.out.println("ENTER CORRECT VALUES");
}
});
// Transform message: Add prediction information
KStream<String, Object> transformedMessage = predictionInput.mapValues(value -> value + ", " + watts);
// Send prediction information to Output Topic
String outputTopic = getProperty("outputTopic");
transformedMessage.to(outputTopic);
// Start Kafka Streams Application to process new incoming messages from Input
// Topic
final KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration);
streams.cleanUp();
streams.start();
// Add shutdown hook to respond to SIGTERM and gracefully close Kafka
// Streams
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}
}
My appContext.xml contains:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hz="http://www.hazelcast.com/schema/spring"
xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.hazelcast.com/schema/spring http://www.hazelcast.com/schema/spring/hazelcast-spring-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd ">
<context:annotation-config />
<context:component-scan base-package="com.escomled" />
<context:component-scan base-package="com.escomled.*" />
<import resource="classpath*:config/blackBoard.xml" />
<task:annotation-driven />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:///home/escomled/escomled_server/config/escomled.properties</value>
</list>
</property>
</bean>
<bean id="reportJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="blackboard" class="com.escomled.blackboard.impl.BlackboardImpl">
<property name="hazelcastInstance" ref="hazelcastClient" />
</bean>
</beans>
I also have an app called escomled_common which contains com.escomled.blackboard.impl package. In that package I implement blackboard with a class called BlackboardImpl.java
BlackboardImpl.java content
...#Component("blackboard")
public class BlackboardImpl implements Blackboard {
private HazelcastInstance hazelcastInstance;
#Override
public HazelcastInstance getHazelcastInstance() {
return hazelcastInstance;
}
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}...
I get an error
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blackboard' defined in class path resource [appContext.xml]: Cannot resolve reference to bean 'instance' while setting bean property 'hazelcastInstance'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'instance' is defined
Someone help ?
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 6 years ago.
I am a newbie to Spring and I am trying to load properties file using Spring framework, I am able to successfully load all the properties from junit test but when I am trying to implement the unit test as function it throws NPE-
my junit class (which is working as expected)
#RunWith(SpringJUnit4ClassRunner.class)
#ActiveProfiles(profiles = "test")
#ContextConfiguration("classpath:spring/xml-config-context.xml")
public class GlueTestPropertiesTest2 extends TestCase {
#Autowired
GenericEnv env;
#Autowired
WebPropertiesLoader wpl;
#Test
public void testAppProperties() {
System.out.println("Running MiniConfigSpringPropertiesTest ...");
System.out.println("Environment : " + env.toString());
System.out.println("Database Properties: " + wpl.toString());
}
}
My implementation class (Which is exhibiting NPE) :
#ActiveProfiles(profiles = "test")
#ContextConfiguration("classpath:spring/xml-config-context.xml")
public class GlueTestProperties {
#Autowired
GenericEnv env;
#Autowired
WebPropertiesLoader wpl;
public static void main(String[] args) {
GlueTestProperties gp = new GlueTestProperties();
gp.callme();
}
private void callme(){
System.out.println("Running ConfigSpringPropertiesTest ...");
System.out.println("Environment : " + env.toString());
System.out.println("Database Properties: " + wpl.toString());
}
}
WebPropertiesLoader bean :
#Component
public class WebPropertiesLoader {
#Value("${bank.ease.login.url}")
public String easeLoginUrl;
#Value("${bank.browser.name}")
public String browserName;
#Value("${bank.browser.version}")
public String browserVersion;
#Value("${webdriver.chrome.driver}")
public String chromeDriver;
#Value("${webdriver.ie.driver}")
public String ieDriver;
#Value("${bank.web.feature.location}")
public String webFeatureLocation;
#Value("${bank.web.test.location}")
public String webTestLocation;
#Value("${bank.event.log}")
public String eventLog;
#Value("${bank.epoxy.backend}")
public String epoxyBackend;
#Value("${bank.epoxy.host}")
public String epoxyHost;
#Value("${bank.epoxy.port}")
public String epoxyPort;
#Value("${bank.epoxy.debug}")
public String epoxyDebug;
#Value("${bank.epoxy.implicitWait}")
public String epoxyImplicitWait;
#Value("${bank.epoxy.timeout}")
public String epoxyTimeOut;
#Value("${bank.epoxy.default.url}")
public String epoxyDefaultURL;
#Value("${bank.sassy.url}")
public String sassyUrl;
#Value("${bank.transite.url}")
public String transiteUrl;
#Value("${bank.transite.login.url}")
public String transiteLoginUrl;
public String getBrowserName() {
return browserName;
}
public String getBrowserVersion() {
return browserVersion;
}
public String getChromeDriver() {
return chromeDriver;
}
public String getEpoxyDefaultURL() {
return epoxyDefaultURL;
}
public String getSassyUrl() {
return sassyUrl;
}
public String getTransiteUrl() {
return transiteUrl;
}
public String getTransiteLoginUrl() {
return transiteLoginUrl;
}
public String getIeDriver() {
return ieDriver;
}
public String getWebFeatureLocation() {
return webFeatureLocation;
}
public String getWebTestLocation() {
return webTestLocation;
}
public String getEventLog() {
return eventLog;
}
public String getEpoxyBackend() {
return epoxyBackend;
}
public String getEpoxyHost() {
return epoxyHost;
}
public String getEpoxyPort() {
return epoxyPort;
}
public String getEpoxyDebug() {
return epoxyDebug;
}
public String getEpoxyImplicitWait() {
return epoxyImplicitWait;
}
public String getEpoxyTimeOut() {
return epoxyTimeOut;
}
public String getEaseLoginUrl() {
return easeLoginUrl;
}
#Override
public String toString() {
return "Ease application Default Properties [browserName=" + browserName + ", browserVersion=" + browserVersion
+ ", chromeDriver=" + chromeDriver + ", ieDriver=" + ieDriver + ", webFeatureLocation="
+ webFeatureLocation + ", webTestLocation=" + webTestLocation + ", eventLog=" + eventLog
+ ", epoxyBackend=" + epoxyBackend + ", epoxyHost=" + epoxyHost + ", epoxyPort=" + epoxyPort
+ ", epoxyDebug=" + epoxyDebug + ", epoxyImplicitWait=" + epoxyImplicitWait + ", epoxyTimeOut="
+ epoxyTimeOut + ", epoxyDefaultURL=" + epoxyDefaultURL + ", easeLoginUrl=" + easeLoginUrl + "]";
}
}
Test env bean :
#Component
public class TestEnv implements GenericEnv {
private String envName = "test";
#Value("${profile.name}")
private String profileName;
public String getEnvName() {
return envName;
}
public void setEnvName(String envName) {
this.envName = envName;
}
public String getProfileName() {
return profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
#Override
public String toString() {
return "TestEnv [envName=" + envName + ", profileName=" + profileName
+ "]";
}
}
Context xml used :
?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- scans for annotated classes in the com.company package -->
<context:component-scan base-package="com.glue.commons" />
<!-- enables annotation based configuration -->
<!-- <context:annotation-config /> -->
<beans profile="dev">
<!-- allows for ${} replacement in the spring xml configuration from the
application-default.properties, application-dev files on the classpath -->
<context:property-placeholder
location="classpath:properties/application-web-default.properties, classpath:properties/application-web-dev.properties"
ignore-unresolvable="true" />
<!-- scans for annotated classes in the com.env.dev package -->
<context:component-scan base-package="com.glue.env.dev" />
</beans>
<beans profile="test">
<!-- allows for ${} replacement in the spring xml configuration from the
application-default.properties, application-test files on the classpath -->
<context:property-placeholder
location="classpath:properties/application-web-default.properties, classpath:properties/application-web-qa2.properties"
ignore-unresolvable="true" />
<!-- scans for annotated classes in the com.env.test package -->
<context:component-scan base-package="com.glue.env.test" />
</beans>
<beans profile="prod">
<!-- allows for ${} replacement in the spring xml configuration from the
application-default.properties, application-prod files on the classpath -->
<context:property-placeholder
location="classpath:properties/application-web-default.properties, classpath:properties/application-web-prod.properties"
ignore-unresolvable="true" />
<!-- scans for annotated classes in the com.env.prod package -->
<context:component-scan base-package="com.glue.env.prod" />
</beans>
<beans profile="dev">
<!-- allows for ${} replacement in the spring xml configuration from the
application-default.properties, application-dev files on the classpath -->
<context:property-placeholder
location="classpath:properties/application-api-default.properties, classpath:properties/application-api-dev.properties"
ignore-unresolvable="true" />
<!-- scans for annotated classes in the com.env.dev package -->
<context:component-scan base-package="com.glue.env.dev" />
</beans>
<beans profile="test">
<!-- allows for ${} replacement in the spring xml configuration from the
application-default.properties, application-test files on the classpath -->
<context:property-placeholder
location="classpath:properties/application-api-default.properties, classpath:properties/application-api-qa2.properties"
ignore-unresolvable="true" />
<!-- scans for annotated classes in the com.env.test package -->
<context:component-scan base-package="com.glue.env.test" />
</beans>
<beans profile="prod">
<!-- allows for ${} replacement in the spring xml configuration from the
application-default.properties, application-prod files on the classpath -->
<context:property-placeholder
location="classpath:properties/application-api-default.properties, classpath:properties/application-api-prod.properties"
ignore-unresolvable="true" />
<!-- scans for annotated classes in the com.env.prod package -->
<context:component-scan base-package="com.glue.env.prod" />
</beans>
Thanks in advance, please forgive me if I've made some silly mistake, but I need your help.
If you use the main method to create it then spring won't know anything about this class so it won't autowire any classes - you get nulls in all fields annotated with #Autowired.
Your JUnit is working correctly because it is instantiated with spring aware junit runner.
I am able to get the properties to load. Issue was that as #krzyk pointed out my implementation class was not spring aware hence it was not able to load the profile from my context xml and to make it aware of my profile bean I had to pass vm argument through my main class, following code change and approach helped me :
my implementation class look like this now:
#ContextConfiguration("classpath:spring/xml-config-context.xml")
public class GlueTestProperties {
private GlueTestProperties() {
}
private static ApplicationContext context;
public static GenericEnv getEnv() {
return getContext().getBean(TestEnv.class);
}
public static WebPropertiesLoader getWebProperties() {
return getContext().getBean(WebPropertiesLoader.class);
}
public static ApiPropertiesLoader getApiProperties() {
return getContext().getBean(ApiPropertiesLoader.class);
}
private static ApplicationContext getContext() {
if (null == context) {
init();
}
return context;
}
private static synchronized void init() {
context = new ClassPathXmlApplicationContext("spring/xml-config-context.xml");
}
}
I am passing following as vm argument : -Dspring.profiles.active=test
Or second approach would be you have to take out
<context:property-placeholder
location="classpath:properties/application-web-default.properties, classpath:properties/application-web-qa2.properties"
ignore-unresolvable="true" />
from your <bean/> and place it out side so that it will be visible for main class and you do not have to pass vm arguments here.