SpringApplicationBuilder parent webapp and child without webapp doesn't work - java

I have a spring boot app with a parent application context and a child application context with some legacy code. I would like to have a webapp in the parent application context, and have the child context be a non webapp.
I have my config and properties in application.yml, that gets loaded in the main class
#ComponentScan(...)
#PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication(
public static void main(String[] args) {
new SpringApplicationBuilder(MyApplication.class)
.profiles("Prod")
.web(WebApplicationType.SERVLET)
.listeners(new MainAppListener()) // logging for some of the events
.child(LegacyServiceConfig.class)
.web(WebApplicationType.NONE)
.listeners(new LegacyAppListener()) // logging for some of the events
.run(args);
}
}
What I've tried so far:
I don't have any web application type config in my application.yml (spring.main.web-application-type). I hoped that the configuration I've specified thru code, in the above snippet would have worked, but it doesn't. Neither of the application contexts start as a webapp, effectively ignoring the config web(WebApplicationType.SERVLET) in the above snippet.
I tried putting spring.main.web-application-type=servlet in my
application.yaml. But that seems to apply this config to both parent
and child application context. And both of them try to start as
webapps, which is not what I want.
How do I get this to work? Any pointers?

As per my knowledge in spring-boot start from main only and the main class is provided by Maven, because I had worked on Maven project. All the properties in the project like JDBC connection, port change you can do it in .properties(extension) type file. And this file can also be in format of .yml also. These file is totally different from main class.
If you make any changes in main or add any extra annotation in main then it will throw an error.
So keep every properties in .properties or .yml file and all configuration component scan in pom.xml file you can have two .properties file also
But main class should be simple like this:
#SpringBootApplication()
public class SpringBootProjectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootProjectApplication.class, args);
}
}
Hope this will help.

Related

How to exposure spring boot actuator endpoints without using application.properties file?

How can I enable and exposure actuator endpoints in Spring boot 2.5.8 application if I don't have access to application.properties file?
It's easy to do with application.properties file, just configuring
management.endpoints.web.exposure.include=*
But if I don't have access to application.properties, how can I do it in code?
You can add the properties as environment variables. Just need to switch casing and . to _
MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE=*
You can use command line to do the same.
mvn spring-boot:run -Dspring-boot.run.jvmArguments='Dmanagement.endpoints.web.exposure.include=*'
Finally, I found 2 solutions.
To use SpringApplication.setDefaultProperties() method before run application:
public class MyApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MyApplication.class);
app.setDefaultProperties(Collections.singletonMap("management.endpoints.web.exposure.include", "*"));
app.run(args);
}
}
Second approach requires access to properties file.
To open properties file with PropertiesConfiguration (this class can both: read properties from file and write new properties/values to file).
Checked if property already exist
If not exist - add it.
PropertiesConfiguration config = getConfig(filePathToPropertiesFile);
if (null == config.getString("management.endpoints.web.exposure.include")) {
config.setProperty("management.endpoints.web.exposure.include", "*");
config.save();
}
All this actions also need to perform in main method before application run.

Springboot app read different path when run local vs package maven

So, I am developing an app and trying to use #ImportResource in the main class to refer to a xml file that contain configuration for SOAP services. When I am trying to run/debug in my local it's working just fine, but when I use maven package to build jar, it produce java.io.FileNotFoundException error.
Here is my main class
#SpringBootApplication
#ImportResource(locations = "jaxwsconfig.xml")
public class SoapApplication {
public static void main(String[] args) {
SpringApplication.run(SoapApplication.class, args);
}
#Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new WSSpringServlet(), "/Services");
}
}
Here is some errors I got when I use maven package
IOException parsing XML document from ServletContext resource [/jaxwsconfig.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/jaxwsconfig.xml]
PS: I have a question about the filepath. Where does Java Spring refer to when I don't define absolute path? Like in this case when I just define "jaxwsconfig.xml", where does it refer to?
If your jaxwsconfig.xml file is under the resource folder ie src/main/resource, you can directly give it as,
#ImportResource({"classpath*:applicationContext.xml"})
If suppose the file is present inside a folder inside resource src/main/resource/foldername. you have to give as,
#ImportResource(locations = {"classpath:foldername/application-context.xml"})

Spring junit configuration

I have tried many configurations. I try to invoke simple System.out as a test to check my configuration :
public class DaoTest {
#Test
public void commentTest() {
System.out.println("test working");
}}
My configuration classes use properties file to get the values and class that holds string constants values:
public static final String DATASOURCE_PATH = "dataSource.driver_class_name";
I annotated the test class with:
#RunWith(SpringJUnit4ClassRunner.class)
#PropertySource(
value={"classpath:spring.properties"},
ignoreResourceNotFound = true)
#ContextConfiguration(classes = { TestConfig.class, ConfigurationConstants.class, ApplicationConfigCore.class, HibernateConfig.class})
#WebAppConfiguration()
#ActiveProfiles(profiles = "test")
Where's TestConfig basically consists of classpath because I tried different ways yet still don't know where's my mistake.
Also i added the spring.properties file both to the resources file of main as well as test package.
So the question I have is where's mistake and when we deploy web app in spring it takes resources from src/main/resources folder, so what's the case with tests. Is it gonna be: src/test/resources?
In case of tests that takes the configuration, like my case, from main app configuration classes - do those classes will find right src/main/resources folder or will they try to check for test/./properties file ?
BTW. when location of properties added to #ContextConfiguration i got
Cannot process locations AND classes for context configuration exception

How to force the import/loading of rest controller programatically

I'm starting a spring boot rest service which may load different packages depending on the distribution. This means sometimes the distribution will contain some jars where certain REST controllers are, sometimes this controllers are not there.
So How I'm able to tell spring-boot where to find the controllers with a configuration files. Now I'm sending this info by annotations forcing me to create a "main" per distribution. I will like to define a unique main that imports the controllers defined in a file. In other words I want to access the #Importannotation manually as is shown in the sniped bellow:
#Configuration
#PropertySource("conf.cfg")
#Import(value = {RestContorller1.class, RestContorller2.class})
#EnableAutoConfiguration
#ConfigurationProperties
#SpringBootApplication
#RestController
#EnableSwagger2
public class Application {
public static void main(String[] args) {
String confFile = Const.DEFAULT_CONFIGURATION_FILE;
if(args.length>0)
confFile= args[0];
System.setProperty("spring.config.name",confFile);
Boolean hasStarted = DataProcessingCore.start(confFile);
if(hasStarted) {
SpringApplication springApp = new SpringApplication(Application.class);
try {
springApp.setDefaultProperties(Utils.createPropertyFiles(confFile));
} catch (IOException e) {
e.printStackTrace();
}
springApp.addInitializers();
springApp.run(args);
}
}
}
If I understand you corretly, your controllers reside in a JAR imported by maven/gradle to your main project/s.
In order to create auto-configuration like spring boot does, that in the same way can be used to import your controllers when the jar is in the classpath, you can tell spring to find your custom configuration on start-up.
I wrote a simple example for that here: Creating your own auto-configuration
In pricipal, you create a spring-boot application (without the spring boot maven plugin!! it is important for the classpath and packaging). and create a file named spring.factories (you can find the actual content in the guide I linked) that tells any spring-boot application that have this jar to load your configuration that may do a #ComponentScan to search for your controllers or set the #Bean manually.
Doing that, you don't have to do #Import and the controllers will be loaded dynamically.

Java Main class overriding properties file at runtime

I am using Apache Maven and Spring. In the src/main/resources folder I have a properties file. These property values can have different values.
I am using PropertyPlaceholderConfigurer.
#Configuration
public class ResourceConfig {
#Bean
public PropertyPlaceholderConfigurer properties( ) {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setIgnoreResourceNotFound(true);
ppc.setLocations(new ClassPathResource[] {new ClassPathResource("propertiesFile")});
return ppc;
}
}
I replace these values at runtime:
#Configuration
public class DataSourceConfig {
#Value("${jdbc.url}")
private String jdbcUrlDefault;
}
This is just a sample. I have a main method:
public static void main(String[] args) {
// accept a properties file and replace those values defined in DataSourceConfig class
}
When Apache Maven builds the application the properties file will be on the classpath. The properties file are used during the unit testing. I want to some how replace the properties with a new properties file before the main program is launched for production.
I have seen some example of Properties.load(), but I don't want to do this. I want to accept a properties file through the main program that gets replaced, so the Spring side starts the PropertyPlaceholderConfigurer.
How can this be achieved?
you can place your test properties files in src/test/resources/. In test classes, it will use properties file from this location.
properties file placed here above location will not included in your classpath in final build.
use src/main/resources to place resource files that you want in main program

Categories