Spring Boot: How to change the path to serve static files? - spring-boot

I have a Spring Boot project located in the path "C:\Personal Projects\Spring" and I want it to serve to browser static HTML file named index.html that is placed in "C:\Personal Projects\Game\build".
Therefore, I wrote the following code:
#SpringBootApplication
#EnableAutoConfiguration
public class Main {
public static void main(String[] args) throws IOException {
SpringApplication app = new SpringApplication(Main.class);
Properties properties = new Properties();
properties.setProperty("spring.resources.static-locations",
"C:\\Personal Projects\\Game\\build");
app.setDefaultProperties(properties);
app.run(args);
}
}
When I run the program and open browser for "localhost:8080/index.html" I get a 404 error.
Do you know what I'm doing wrong?

It should be:
properties.setProperty("spring.resources.static-locations",
"file:C:\\Personal Projects\\Game\\build");

Related

Accessing static resources in Spring Boot v2.1.7.RELEASE

I am very new to Spring-Boot and Bootstrap.
I'm trying to load static resources, and this is what my project structure looks like.
I saw that Spring-boot-starter lets "/" to access "/static", so if I add tag like on the screenshot I uploaded,
<script src="/js/app/index.js"></script>
then it should load file from /src/main/resources/static/js/app/index.js.
I tried every solution I saw on stackoverflow and google, but I couldn't find the answer.
Please help me.
Also, my Application.java file is as described below.
#EnableJpaAuditing
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
If I Build my application and load it, web browser console messages says
net::ERR_ABORTED 404 on every static resources that I try to load.
Spring boot will automatically serve any resources under the directories :
/META-INF/resources/
/resources/
/static/
/public
but you have a sub folder /app in your project for these static asssets. So if you keep everything like :
/static/css/
/static/js/
and so on it should work. Or else you could provide your own folder structure for the static assets by customizing the bean like :
#Configuration
public class StaticConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/custom/");
}
}

Logging using spring boot sl4j

In my application properties i have written the below for logging
logging.level.com.intro.dmp=INFO
logging.level.org.springframework.web=ERROR
logging.level.com.intro.dmp=ERROR
logging.file=application.log
and my Application is below , but it is not creating any log file rather displaying in the console . What is that i am missing here , it is reading application properties
#SpringBootApplication(scanBasePackages = "com.intro")
#PropertySource("file:src/main/resources/application.properties")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
logger.debug("--Application Started--");
logger.error("Check the main Articles");
logger.info("Checking files ");
}
}
Two changes will resolve your issue:
In application.properties file, you need to provide quotes to the file name. i.e.:logging.file='application.log'
You can remove #PropertySource annotation. Spring Boot will, by default, look for application.properties file at src/main/resources/.

Spring Boot not using application.properties for spring.groovy.template.cache

I have a very simple Spring Boot application with classes detailed below.
My problem is with the application.properties file and how they get auto-configured. I'm trying to get Groovy Templates to update in dev by setting 'spring.groovy.template.cache: false', however this is not working. I added two more properties to see if the application.properties file was being read. The 'logging.level.org.springframework.web: ERROR' still results in INFO level messages printed to the console. However, some.prop is read correctly into the MyBean class on application start.
Is there a configuration declaration I'm missing for these properties?
src/main/resources/application.properties:
spring.groovy.template.cache: false
logging.level.org.springframework.web: ERROR
some.prop: bob
src/main/java/sample/MyBean.java:
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
public MyBean() {}
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
and src/main/java/sample/Application.java:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and src/main/java/sample/com/example/MainController.java
#Controller
public class MainController {
#RequestMapping(value="/login", method = RequestMethod.GET)
public ModelAndView risk(#RequestParam Optional<String> error) {
return new ModelAndView("views/login", "error", error);
}
}
It seems you missing scanned your package "sample". Please make sure that you have scanned it.
#ComponentScan({
"sample" })
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also, your application.properties is right. No problem with it.
It appears the solution was much simpler than I thought:
gradle bootRun
should be used to hot reload templates
gradle run does not work (all compiled classes are just built in build/ )

Loading applicationcontext.xml when using SpringApplication

Could anyone provide an example of a SpringApplication that loads an applicationContext.xml file?
I'm attempting to move my GWT RPC application to a RESTful web service by using a Spring's Example (Gradle based). I have an applicationContext.xml but I do not see how to get SpringApplication to load it. Loading manually via
ApplicationContext context = new ClassPathXmlApplicationContext(args);
results in an empty context. ...and even if that worked it would be separate from the one returned from
SpringApplication.run(Application.class, args);
Or is there a way to get external beans into the app context created by SpringApplication.run?
If you'd like to use file from your classpath, you can always do this:
#SpringBootApplication
#ImportResource("classpath:applicationContext.xml")
public class ExampleApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ExampleApplication.class, args);
}
}
Notice the classpath string in #ImportResource annotation.
You can use #ImportResource to import an XML configuration file into your Spring Boot application. For example:
#SpringBootApplication
#ImportResource("applicationContext.xml")
public class ExampleApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ExampleApplication.class, args);
}
}
The annotation does not have to be (on the class) that (has the main method) that (has this below call):
SpringApplication.run(Application.class, args);
(in your case, what I am saying is that #ImportResource does NOT have to be on your class)
public class ExampleApplication {}
.........
You can have a different class
#Configuration
#ImportResource({"classpath*:applicationContext.xml"})
public class XmlConfiguration {
}
or for clarity
#Configuration
#ImportResource({"classpath*:applicationContext.xml"})
public class MyWhateverClassToProveTheImportResourceAnnotationCanBeElsewhere {
}
The above is mentioned in this article
http://www.springboottutorial.com/spring-boot-java-xml-context-configuration
.........
BONUS:
And just in case you may have thought "SpringApplication.run" was a void method.....that is NOT the case.
You can also do this:
public static void main(String[] args) {
org.springframework.context.ConfigurableApplicationContext applicationContext = SpringApplication.run(ExampleApplication.class, args);
String[] beanNames = applicationContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String name : beanNames) {
System.out.println(name);
}
This will also subtly clue you in to all the many, many, many (did I mention "many"?)....dependencies that spring boot is bringing in. Depending to whom you speak, this is a good thing (somebody else did all the nice figuring out for me) or an evil thing (whoah, that's a lot of dependencies that I don't control).
hashtag:sometimesLookBehindTheCurtain
Thanks Andy, that made it very concise. However, my main problem turned out to be getting applicationContext.xml into the classpath.
Apparently, putting files into src/main/resources is required to get them into the classpath (by placing them into the jar). I was attempting to set CLASSPATH which was just ignored. In my example above, the load seemed to fail silently. Using #ImportResource caused it to fail verbosely (which helped me track down the real cause).

Spring Boot WS application cannot load external property

In my Spring-Boot Web Service application, I want to load a property named appName with value defined in application.properties.
#Endpoint
public class RasEndpoint {
private static final String NAMESPACE_URI = "http://www.mycompany.com/schema/ras/ras-request/V1";
#Value("${appName}")
private String appName;
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getProductRequest")
#ResponsePayload
public GetProductResponse getProduct(#RequestPayload GetProductRequest request) {
System.out.println("appName: " + appName);
GetProductResponse response = generateStubbedOkResponse();
return response;
}
application.properties has the following entry
appName=ras-otc
I get the application started via the main Application class as shown below
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
However, when I run the app, I get the following error
Caused by: java.lang.IllegalArgumentException: Could not resolve
placeholder 'appName' in string value "${appName}"
Do you guys know what I'm doing wrong?
Appreciate any help.
As Dave mentioned in the comment above, the properties file was not loaded into the classpath.
The properties file was located in /src/main/resources folder, which was added to source, under build path in Eclipse IDE, however had an exclusion rule applied which prevented the properties file from being loaded into the classpath. By removing the exclusion, I was able to load the properties correctly.

Resources