File can not be loaded from src/test/resources while working on spring boot junit tests - spring-boot

I created one folder src/test/resources and added one file Test.json and trying to access in junit test like this
#RunWith(SpringRunner.class)
#WebMvcTest(value = ReadController.class, secure = false)
public class ReadControllerTest {
#Value("${classpath:Test.json}")
Resource testFile;
#Test
public void test() throws Exception{
File file = testFile.getFile();
System.out.println(file.exists());
}
}
When I run this unit test, it tries to find file in classpath but file is not present there.
How to add this file in classpath?

By Default, spring boot classpath will be pointed to src/main/resources but you are using src/test/resources.
Try to copy the JSON file to src/main/resources.

Related

Springboot Jboss system property issue

In our Springboot MVC project we need to get context path. The following code works fine if we use embedded tomcat. Otherwise if we deploy war file to jboss server, context path returns null.
I tried to add context-root property to jboss-web.xml but changed nothing. I also tried to add "server.servlet.contextPath" property to application.properties file but it doesn't work.
Spring boot version : 2.2.0.RELEASE
Code:
#Configuration
public class EurekaClientConfigBeanListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
String pathValue = System.getProperty("server.servlet.contextPath");
}

Spring - Run test from IDE - how to load test properties from a file like 'application-test.properties'

How can I load test properties from a file like 'application-test.properties'?
The file is stored in the src/test/resources folder. I put the file also in all possible folders as well. When running the test as part of the Maven test run, all works fine.
When running the new (single) test from the (IntelliJ) IDE, each time I get same the error message:
Caused by: java.io.FileNotFoundException: class path resource
[application-test.properties] cannot be opened because it does not
exist
This is the test class:
#RunWith(SpringRunner.class)
#EnableAutoConfiguration
#ComponentScan(basePackages = {"nl.deholtmans.tjm1706.todolist"})
#PropertySource( "application-test.properties")
public class TodoListServiceTest {
#Autowired
TodoListService todoListService;
#Test
public void testBasic() { ... }
It looks that I have to run the test first time from Maven. Why is that?
Spring Boot will automatically load the correct properties file if the profile is activated. In a test you can use the #ActiveProfiles annotation for that.
Next you would need to make sure that you actually use the proper Spring Boot infrastructure to run your test, using #SpringBootTest. That being said your test header should look something like the following
#RunWith(SpringRunner.class)
#SpringBootTest
#ActiveProfiles("test")
public class TodoListServiceTest { ... }
And ofcourse make sure that your IDE builds the application before running the tests.

How can I load additional properties file in a spring boot application packaged as a war?

I have a standard springboot web app. I want to load properties file that's not in the classpath. application.properties is in the classpath and is being read correctly.
I don't have an issue when I'm building a jar. I just put the .properties alongside the jar and it works. But when I package a war, I couldn't get the application to read the properties file .
You put the properties file parallel to application.properties file and load it in a class like this:
#PropertySource("classpath:foo.properties")
public class My class {
#Value( "${some.property}" )
String myProp;
}
You can using ClassPathResource. given Class for loading resources.
This is sample code for you
ClassPathResource resource = new ClassPathResource("/application/context/blabla.yml");
InputStream inputStream = resource.getInputStream();
File file = resource.getFile();
// using inputStream or file
ClassPathResource
You can use spring application.properties to have spring profiles and use the spring profiles to define separate properties for each environment as you like.You can even separate out the spring profiles in to different files like appication-dev.properties etc so that you can have each spring profile in different files.
You can read the properties by using #Configuration annotation :
#Configuration
#EnableConfigurationProperties(TestProperties.class)
public class MySampleConfiguration {
}
Here TestProperties.class is used to map the values from the property file or yaml .
Reference in detail : https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Spring Boot 2 : How to load each application.yml files of different modules into a given web or batch runner

I create a Spring Boot Application, and I'm wondering if it is possible to load upmteens application.yml files of different modules.
I have this structure :
myProject
|__ moduleCommons
| |__ application.yml
|__ moduleWeb
| |__ application.yml
| |__ MyProjectWebApplication.java
|__ moduleBatch
|__ application.yml
|__ MyProjectBatchApplication.java
To launch the Spring Boot application of web module, I run the MyProjectWebApplication.java.
To launch a Spring Batch of batch module, I run the MyProjectBatchApplication.java.
Both of them need some commons properties, which are set in application.yml file of commons module (like database configuration, directory paths for upload files, etc.).
And some others properties are specific to each module, so set in application.yml file of web module (like servlet context path, jwt settings) or batch module (like mailer settings).
And, for example, MyProjectWebApplication class into which i would like to load web and commons application.yml files :
package com.myProject.web;
#SpringBootApplication(
scanBasePackages = {"com.myProject.web", "com.myProject.commons"},
exclude = {DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class}
)
#EnableJpaRepositories(
basePackages = "com.myProject.commons.datasources.defaut.repository",
repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class
)
#ContextConfiguration(classes = {MyProjectDbConfig.class})
public class MyProjectWebApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyProjectWebApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyProjectWebApplication.class, args);
}
}
But it seems I load only web module application.yml file with this configuration...
Help ! :)
You could make it by setting application.yml in common module and /config/application.yml in the depending modules. If you need a third fallback for test you can use /config/application-test.yml with #ActiveProfiles("test") on every #Test.
That way your set up would be: test properties -> main properties -> commons properties
This works on a build-from-scratch testcase, but I am not sure of the consequences of having main properties under config when running on different environments (https://github.com/spring-projects/spring-boot/issues/9128, i.e, whether commons application.yml is guaranteed to precede other dependencies potential ones)
You can rename your application file in common module to application.yaml or application.propertes, and don't change it in other modules. It's a hack, but it's work. If you use same files in your target and common module, Spring will take only one, which in target module. So you need to add another default file or one more profile.

Spring Boot - deploy .properties file to a folder different than 'WEB-INF/classes'

I'm trying to convert a traditional Tomcat Spring MVC webapp to Spring Boot. The new application should still use .war deployment.
For various reasons I have the obligatory requirement that the application.properties file resides inside a WEB-INF/conf folder in the deployed app and NOT inside the WEB-INF/classes folder where Spring Boot puts it by default.
In the original webapp I could put the application.properties file inside the src/main/webapp/WEB-INF/conf folder (so they get copied to WEB-INF/conf in the deployed application) and then use it like this:
<context:property-placeholder location="/WEB-INF/conf/application.properties"/>
What is the Spring Boot way to refer to this location?
I tried adding each of the following:
spring.config.location=WEB-INF/conf/application.properties
but my application.properties file still doesn't get loaded.
What finally worked was the following #PropertySource annotation.
#SpringBootApplication
#PropertySource(value = {"WEB-INF/conf/application.properties"})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
It seems that not specifying classpath: or file: at the beginning of a path makes it use a path relative to the webapp.
I'm still not sure as to why specifying
spring.config.location=WEB-INF/conf/application.properties
didn't have the same effect.

Resources