Wednesday, May 16, 2012
How can I read a resource relative to the classpath ?
How can I read a resource relative to the classpath ?
You have to get the applicationcontext. I have blogged on this topic.
a) Create a resource that has a reference to a path
example :
public org.springframework.core.io.Resource getResource() {
logger.debug("entering getResource");
org.springframework.core.io.Resource resource = applicationContext.getResource("classpath:telemetry/telemetrieA+Cons20090101_200906112209055.csv");
logger.debug("leaving getResource");
return resource;
}
b) Read the resource
example :
CSVReader reader = new CSVReader(new FileReader(getResource().getFile()));
That's all folks !
How can I access the spring context ?
How can I access the spring context ?
There are 2 cases :
a) In an application
b) In a test application
a) In an application
1) You have to implement the interface ApplicationContextAware
example :
public class TelemetryConsumptionSynchronizer extends BaseSynchronizer implements ApplicationContextAware
2) Implementation of the method setApplicationContext
...
ApplicationContext applicationContext;
...
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
logger.debug("entering setApplicationContext");
this.applicationContext = applicationContext;
logger.debug("leaving setApplicationContext");
}
b) In a test application
It is more easy because you only have to inject the context.
example :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {
"classpath:el1EnergyCommSyncContextTest.xml"
}
)
public class TelemetryConsumptionSynchronizerTest {
...
@Resource
private ApplicationContext applicationContext;
}
There are 2 cases :
a) In an application
b) In a test application
a) In an application
1) You have to implement the interface ApplicationContextAware
example :
public class TelemetryConsumptionSynchronizer extends BaseSynchronizer implements ApplicationContextAware
2) Implementation of the method setApplicationContext
...
ApplicationContext applicationContext;
...
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
logger.debug("entering setApplicationContext");
this.applicationContext = applicationContext;
logger.debug("leaving setApplicationContext");
}
b) In a test application
It is more easy because you only have to inject the context.
example :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {
"classpath:el1EnergyCommSyncContextTest.xml"
}
)
public class TelemetryConsumptionSynchronizerTest {
...
@Resource
private ApplicationContext applicationContext;
}
Subscribe to:
Comments (Atom)
