I tried to implement a “Hello Word” demo with Spring 4 that maps the "/" http request to a method call. I found an example doing this but wanted to do the same from scratch. I got it running, the implementation classes (application and controller) do not deviate from the demo but the request mapper in my own app causes an error handler to be called. The differences in the log of the running demo and my app:
——>this line is missing in the bad case: [ main]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped
“{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}”
onto public java.lang.String
com.goodvideotutorials.spring.controllers.RootController.home()
Could you please have a look at it and advise me why the request mapping does not work in my case? Thank you also in advance. The code sample I copied below:
Application:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller:
#RestController
public class RootController {
#RequestMapping("/")
public String home(){
return "Hello World!";
}
}
In spring boot applications, the Bean that are found be automatic class scanning must be located in subpackges (or the same package) of the package that contains the class that is used to start the application.
Related
I created a simple SpringBoot application using "http://start.spring.io" Spring Initializr. I am using JDK 8 and Spring 2.6.6.
I opened an application in IntelliJ and was able to build it and run it. I also added "application.properties" as my resource where I defined a property :
application.baseurl=/responsiblityViewer/api
in my DemoApplication.java :
public class DemoApplication {
#Value("${application.baseurl}")
public static String baseUrl;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("Test Application baseUrl : " + baseUrl);
}
}
The output is NULL.
I also tried to use "application.yml" where I defined :
application:
baseurl: /responsiblityViewer/api
and still "application.baseurl" is not getting injected. What am I doing wrong here?
There's a lot to dissect here.
First, you can't inject a value into a static property.
Second, you will not be able to reference that property from a static main method as the bean hasn't been constructed yet.
If you read up on the spring bean lifecycle it will help you to understand this, the injection occurs after instantiation.
You can observe this behavior if you change your variable definition to
public String baseUrl;
and add this method
#PostConstruct
public void printIt() {
log.debug(baseUrl);
}
I used #RequestMapping or #GetMapping for routing.
But, it doesn't work. It makes whitelabel error page.
(spring boot)
my Application.java
#RestController
#SpringBootApplication
public class SmDemoApplication {
#RequestMapping("/")
String home() {
return "Hello World! smDemo 111";
}
public static void main(String[] args) {
SpringApplication.run(SmDemoApplication.class, args);
}
}
And controller is
#RestController
public class WebRestController {
//#GetMapping("/hello")
#RequestMapping(value="/hello", method=RequestMethod.GET)
public String hello() {
return "Hello World! 222";
}
}
http://localhost:8080 is good.
but, http://localhost:8080/hello makes white label error !!
what's the problem in my code?? (I made my project, using spring starter project)
Springboot reads its stereotype beans ,controllers and configurations from package and subpackages of main class,(until you define #ComponentScan to read other packages) I feel your project main class is in another package than the controller i.e. Controller is not in same or in a sub package where Main class is.
For example , If your main package is in
com.xyz.abc
|_ SmDemoApplication
Keep controller,other beans and configuration in com.xyz.abc package like
com.xyz.abc
|_WebRestController
or sub-packages like
com.xyz.abc.controllers
|_WebRestController
I am trying to identify a way to know the name of the Main-Class that started SpringBoot.
e.g.
#SpringBootApplication
public class SampleApplication {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
#RestController
public class SampleController
{
#GetMapping("/hello")
pubic String sayHello()
{
System.out.println("Need start class name: "+System.getProperty("sun.java.command"));
return "hello";
}
}
}
When I run the springboot using java -jar myappname.jar ,the System.getProperty("sun.java.command") returns org.springframework.boot.loader.JarLauncher
Can anyone advise, how can I get the name of actual run class. I have tried specifying the start-class attribute in the manifest.mf. It still gave me org.springframework.boot.loader.JarLauncher as the start-class.
You should be able to #Autowire in the ApplicationContext and then do context.getBeansWithAnnotation(SpringBootApplication.class).values().toArray()[0].getClass().getName(), which will give you the first (and presumably only) bean in the context annotated with #SpringBootApplication
Controller class.
#RestController
#RequestMapping("/check")
public class Controller {
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
Application class
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Added all the necessary dependency when running the application shows the
http://localhost:8081/demo/
Hello World
of index.xml
When I change to http://localhost:8081/check/ it gives
HTTP Status 404 – Not Found
Type Status Report
Message /check
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
How can I understand the flow of Spring Boot application?
You need to put the Http method on your method, here I am assuming you are doing a GET request
#RestController
#RequestMapping("/check")
public class Controller {
#GetMapping // you forgot to put http method here
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
Note: GetMapping is only available if you are using Spring 4.3 or above else use #RequestMapping(value = "/url", method = RequestMethod.GET)
Your controller should be like this:
#RestController
public class Controller {
#RequestMapping(value="/check")
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
}
It seems
#RequestMapping(value="/check") is not working.
switch to
#RequestMapping(path="/check")
though as per documentation it should work.
1.
I'm working with Spring Boot. My Main class very simple
#ComponentScan
#EnableAutoConfiguration
#Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#2. Now I would like to make my static content externalised into a jar file. So, below is the jar project
/pom.xml
/src/main/resources/META-INF/resources/hello.json // here is my resource
I do maven install and put the dependency into the main app, run the app normally. Now I can invoke http://localhost:8080/hello.json to get my hello.json file
#3. Then, the next step is using the Apache Tiles for my main web project, so I create a #EnableWebMvc class to configure the tilesViewResolver
#Configuration
#EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
public #Bean TilesViewResolver tilesViewResolver() {
return new TilesViewResolver();
}
public #Bean TilesConfigurer tilesConfigurer() {
TilesConfigurer ret = new TilesConfigurer();
ret.setDefinitions(new String[] { "classpath:tiles.xml" });
return ret;
}
}
Then I started again the application and try the hello.json to ensure everything still works properly. But, the 404 page appear. Delete the WebMvcConfiguration give back my hello.json.
What configuration I should do to resolve this issue?
Thanks a lot.
In Spring MVC, using XML configuration, you have to have a tag like the following to service static content:
<mvc:resources mapping="/js/**" location="/js/"/>
This insinuates that Spring Boot is doing something to automatically guess that you have static content and properly setup the above example in META-INF/resources. It's not really "magic", but rather that they have a default Java Configuration using #EnableWebMvc that has some pretty reliable default values.
When you provide your own #EnableWebMvc, my guess is you are over-writting their "default" one. In order to add back a resource handler, you would do something like this:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
This is equivalent to the XML above.