I am running sample spring boot application in spring tool suite tool.
After configuring the port I am unable to start application from browser. I am getting 404 Not found error.
Spring boot is running properly on tomcat.
application.properties
hello.greeting= nice to see you
server.port=9874
Could some one please help me to correct the problem.
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class HelloBootApplication {
public static void main(String[] args) {
SpringApplication.run(HelloBootApplication.class, args);
}
}
package demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#Autowired
HelloProperties props;
#RequestMapping("/hello")
public String hello(#RequestParam String name) {
return props.getGreeting()+name;
}
}
package demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
#ConfigurationProperties("hello")
public class HelloProperties {
private String greeting = "Welcome ";
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
2018-07-22 17:17:32.798 INFO 11824 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-22 17:17:32.952 INFO 11824 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-07-22 17:17:33.000 INFO 11824 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9874 (http) with context path ''
2018-07-22 17:17:33.006 INFO 11824 --- [ main] demo.HelloBootApplication : Started HelloBootApplication in 2.083 seconds (JVM running for 2.862)
This is spring boot application, getting 404 Not Found on below link
http://localhost:9874/
Your url is wrong . You have to call the url with RequestParam name.
use this url http://localhost:9874/hello?name=test
Related
I have recently started exploring Spring boot. I am following https://www.bezkoder.com/spring-boot-jdbctemplate-postgresql-example/ documentation.
I have created all files as instructed in the documentation.
Here goes my code:
******AppApplication.java
`package com.triveni.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
}`
***** IProductRepository *****
`package com.triveni.repository;
import com.triveni.models.ProductModel;
import java.util.List;
public interface IProductRepository {
int create(ProductModel productModel);
int update (ProductModel productModel);
ProductModel findById(int id);
List<ProductModel> findAll();
List<ProductModel> findByActive(boolean active);
}`
***** ProductModel.java *****
package com.triveni.models;
public class ProductModel {
private int productId;
private String productName;
private int cost;
private Boolean active;
private int descriptionId;
public ProductModel(int productId, String productName, int cost, Boolean active, int descriptionId){
this.productId = productId;
this.productName = productName;
this.cost = cost;
this.active = active;
this.descriptionId = descriptionId;
}
public void setProductId(int productId){
this.productId = productId;
}
public long getProductId(){
return productId;
}
public void setProductName(String productName){
this.productName = productName;
}
public String getProductName(){
return productName;
}
public void setCost(int cost) {
this.cost = cost;
}
public int getCost() {
return cost;
}
public void setActive(Boolean active) {
this.active = active;
}
public Boolean getActive() {
return active;
}
public void setDescriptionId(int descriptionId) {
this.descriptionId = descriptionId;
}
public int getDescriptionId() {
return descriptionId;
}
}
*** Product Repository *****
package com.triveni.data;
import com.triveni.models.ProductModel;
import com.triveni.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class ProductRepository implements IProductRepository {
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public int create(ProductModel productModel) {
return jdbcTemplate.update("INSERT INTO public.product(\n" +
"\t\"productId\", \"productName\", cost, \"DescriptionId\", active)\n" +
"\tVALUES (?, ?, ?, ?, ?);",new Object[]{productModel.getProductId(),productModel.getProductName(),
productModel.getCost(), productModel.getDescriptionId(),productModel.getActive()});
}
#Override
public int update(ProductModel productModel) {
return 0;
}
#Override
public ProductModel findById(int id) {
return null;
}
#Override
public List<ProductModel> findAll() {
return jdbcTemplate.query("SELECT \"productId\", \"productName\", cost, \"DescriptionId\", active\n" +
"\tFROM public.product",BeanPropertyRowMapper.newInstance(ProductModel.class));
}
#Override
public List<ProductModel> findByActive(boolean active) {
return null;
}
}
***** ProductController.java *****
package com.triveni.controllers;
import java.util.ArrayList;
import java.util.List;
import com.triveni.data.ProductRepository;
import com.triveni.models.ProductModel;
import com.triveni.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/v1")
public class ProductController {
#Autowired
ProductRepository productRepository;
#GetMapping("/product")
public ResponseEntity<List<ProductModel>> getAllProducts(){
try{
List<ProductModel> products = new ArrayList<ProductModel>();
productRepository.findAll().forEach(products::add);;
return new ResponseEntity<>(products, HttpStatus.OK);
}catch (Exception e){
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
My Project Folder Structure
I am getting following error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Dec 27 13:51:39 IST 2022
There was an unexpected error (type=Not Found, status=404).
Any help will be highly appreciated.
*Output
/Users/chhayatiwari/Library/Java/JavaVirtualMachines/openjdk-19.0.1/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=51857:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app/target/classes:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-web/3.0.1/spring-boot-starter-web-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter/3.0.1/spring-boot-starter-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot/3.0.1/spring-boot-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/3.0.1/spring-boot-autoconfigure-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-logging/3.0.1/spring-boot-starter-logging-3.0.1.jar:/Users/chhayatiwari/.m2/repository/ch/qos/logback/logback-classic/1.4.5/logback-classic-1.4.5.jar:/Users/chhayatiwari/.m2/repository/ch/qos/logback/logback-core/1.4.5/logback-core-1.4.5.jar:/Users/chhayatiwari/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.19.0/log4j-to-slf4j-2.19.0.jar:/Users/chhayatiwari/.m2/repository/org/apache/logging/log4j/log4j-api/2.19.0/log4j-api-2.19.0.jar:/Users/chhayatiwari/.m2/repository/org/slf4j/jul-to-slf4j/2.0.6/jul-to-slf4j-2.0.6.jar:/Users/chhayatiwari/.m2/repository/jakarta/annotation/jakarta.annotation-api/2.1.1/jakarta.annotation-api-2.1.1.jar:/Users/chhayatiwari/.m2/repository/org/yaml/snakeyaml/1.33/snakeyaml-1.33.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-json/3.0.1/spring-boot-starter-json-3.0.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.14.1/jackson-databind-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.14.1/jackson-annotations-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.14.1/jackson-core-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.14.1/jackson-datatype-jdk8-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.14.1/jackson-datatype-jsr310-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/module/jackson-module-parameter-names/2.14.1/jackson-module-parameter-names-2.14.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/3.0.1/spring-boot-starter-tomcat-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/10.1.4/tomcat-embed-core-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/10.1.4/tomcat-embed-el-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/10.1.4/tomcat-embed-websocket-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-web/6.0.3/spring-web-6.0.3.jar:/Users/chhayatiwari/.m2/repository/io/micrometer/micrometer-observation/1.10.2/micrometer-observation-1.10.2.jar:/Users/chhayatiwari/.m2/repository/io/micrometer/micrometer-commons/1.10.2/micrometer-commons-1.10.2.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-webmvc/6.0.3/spring-webmvc-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-aop/6.0.3/spring-aop-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-context/6.0.3/spring-context-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-expression/6.0.3/spring-expression-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/slf4j/slf4j-api/2.0.6/slf4j-api-2.0.6.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-core/6.0.3/spring-core-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-jcl/6.0.3/spring-jcl-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-data-jdbc/3.0.1/spring-boot-starter-data-jdbc-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/3.0.1/spring-boot-starter-jdbc-3.0.1.jar:/Users/chhayatiwari/.m2/repository/com/zaxxer/HikariCP/5.0.1/HikariCP-5.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-jdbc/3.0.0/spring-data-jdbc-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-relational/3.0.0/spring-data-relational-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-commons/3.0.0/spring-data-commons-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/postgresql/postgresql/42.5.1/postgresql-42.5.1.jar:/Users/chhayatiwari/.m2/repository/org/checkerframework/checker-qual/3.5.0/checker-qual-3.5.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-jdbc/5.3.22/spring-jdbc-5.3.22.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-beans/6.0.3/spring-beans-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-tx/6.0.3/spring-tx-6.0.3.jar com.triveni.app.AppApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.1)
2022-12-27T20:17:11.351+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : Starting AppApplication using Java 19.0.1 with PID 3695 (/Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app/target/classes started by chhayatiwari in /Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app)
2022-12-27T20:17:11.353+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : No active profile set, falling back to 1 default profile: "default"
2022-12-27T20:17:11.664+05:30 INFO 3695 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2022-12-27T20:17:11.671+05:30 INFO 3695 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 4 ms. Found 0 JDBC repository interfaces.
2022-12-27T20:17:11.919+05:30 INFO 3695 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-12-27T20:17:11.924+05:30 INFO 3695 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-27T20:17:11.925+05:30 INFO 3695 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.4]
2022-12-27T20:17:11.972+05:30 INFO 3695 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-12-27T20:17:11.973+05:30 INFO 3695 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 589 ms
2022-12-27T20:17:12.162+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-12-27T20:17:12.282+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection#6680f714
2022-12-27T20:17:12.283+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-12-27T20:17:12.343+05:30 INFO 3695 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-12-27T20:17:12.348+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : Started AppApplication in 1.206 seconds (process running for 1.435)
2022-12-27T20:19:18.599+05:30 INFO 3695 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-27T20:19:18.599+05:30 INFO 3695 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-12-27T20:19:18.604+05:30 INFO 3695 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
try to add this to annotation #CrossOrigin("*") after #RestController.
I believe you are just launching the spring application and on launch, this error shows up. In order to test your URL you can type
<YOUR-URL>/app/v1/product
This should return you the Response you are looking for.
Remove ResponseEntity<List> from method and instead return a simple String and check if the method invoked or not. If it works properly then go to the next step and invoke the repository.
I am trying to send below Jsonobject as request parameter to rest API.
{ "date": "2022-01-01", "value": [ "TST/USED" ] }
Value field contains the list of values, but when I add the value in this format as part of request it replaces string / to \/ due to which the request is not processing and it throws 415 : [no body] exception.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add(AUTHORIZATION, "Bearer " + token);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
JSONObject req = new JSONObject();
req.put("date", "2022-01-01");
req.put("value", "TST/USED");
HttpEntity<Object> object = new HttpEntity<>(req.toString(), headers);
Object response = restTemplate.exchange(apiUrl, HttpMethod.POST, object, Object.class)
.getBody();
I don't see the issue you mention, here is what I am running:
Main application with Spring boot and a RestTemplate bean.
package com.so.so72424428;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class So72424428Application {
public static void main(String[] args) {
SpringApplication.run(So72424428Application.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
An api to test:
package com.so.so72424428;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ApiEndPoint {
#PostMapping(path = "/test-api", consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String echo (#RequestBody String jsonMessage) {
return jsonMessage;
}
}
A class to run your code:
package com.so.so72424428;
import java.util.Arrays;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;
#Component
#Slf4j
public class So72424428 implements CommandLineRunner {
#Autowired
private RestTemplate restTemplate;
#Override
public void run(String... args) throws Exception {
HttpHeaders headers = new HttpHeaders();
//headers.add(AUTHORIZATION, "Bearer " + token);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject req = new JSONObject();
req.put("date", "2022-01-01");
req.put("value", "TST/USED");
log.info(req.toString());
HttpEntity<Object> object = new HttpEntity<>(req.toString(), headers);
String apiUrl = "http://localhost:8080/test-api";
Object response = restTemplate.exchange(apiUrl, HttpMethod.POST, object, Object.class)
.getBody();
log.info(response.toString());
}
}
When I run the code I print out the content of the req variable:
{"date":"2022-01-01","value":"TST/USED"}
Also after round trip of the request I print out the response:
{date=2022-01-01, value=TST/USED}
This is the log:
2022-05-29 13:39:24.416 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428Application : Starting So72424428Application using Java 15.0.2 on ...)
2022-05-29 13:39:24.418 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428Application : No active profile set, falling back to 1 default profile: "default"
2022-05-29 13:39:24.462 INFO 32332 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-05-29 13:39:24.462 INFO 32332 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-05-29 13:39:25.310 INFO 32332 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-05-29 13:39:25.320 INFO 32332 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-05-29 13:39:25.320 INFO 32332 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-05-29 13:39:25.387 INFO 32332 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-05-29 13:39:25.388 INFO 32332 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 925 ms
2022-05-29 13:39:25.716 INFO 32332 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-05-29 13:39:25.760 INFO 32332 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-05-29 13:39:25.768 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428Application : Started So72424428Application in 1.678 seconds (JVM running for 2.616)
2022-05-29 13:39:25.778 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428 : {"date":"2022-01-01","value":"TST/USED"}
2022-05-29 13:39:25.869 INFO 32332 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-05-29 13:39:25.869 INFO 32332 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-05-29 13:39:25.870 INFO 32332 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2022-05-29 13:39:25.921 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428 : {date=2022-01-01, value=TST/USED}
2022-05-29 13:39:33.346 INFO 32332 --- [on(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
As you can see there is no backslash, nor no issue for completing the request.
I am trying to use spring.gson.disable-html-escaping=false in my spring boot application.
but it is returning default value.
application.properties:
spring.mvc.converters.preferred-json-mapper=gson
spring.gson.disable-html-escaping=false
GsonHttpMessageConverterConfig.java
package com.example.demo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import java.util.*;
import java.util.stream.Collectors;
#Configuration
#Slf4j
public class GsonHttpMessageConverterConfig {
#Value("${grove.gson.http.converter.mediaTypes}")
private String configuredMediaTypes;
#Value("${spring.gson.disable-html-escaping}")
private String disabledHtmlEscaping;
#Bean
#Autowired
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
List<MediaType> configuredMediaTypes = httpConverterMediaTypes();
if (!configuredMediaTypes.isEmpty()){
converter.setSupportedMediaTypes(configuredMediaTypes);
}
converter.setGson(gson());
System.out.println("converter.getGson().htmlSafe() : "+converter.getGson().htmlSafe());
return converter;
}
#Bean
public Gson gson() {
//String disabledHtmlEscaping = System.getenv("spring.gson.disable-html-escaping");
final GsonBuilder builder = new GsonBuilder();
System.out.println("spring.gson.disable-html-escaping : "+disabledHtmlEscaping);
return builder.create();
}
private List<MediaType> httpConverterMediaTypes(){
//String configuredMediaTypes = System.getenv("grove.gson.http.converter.mediaTypes");
if (configuredMediaTypes != null && !configuredMediaTypes.trim().equals("")){
return Arrays.stream(configuredMediaTypes.split(","))
.map(mediaType -> mediaType.split("/"))
.map(mediaType -> new MediaType(mediaType[0],mediaType[1]))
.collect(Collectors.toList());
}
return Collections.emptyList();
}
}
can somebody help me why that property is not working.
I dont want to use builder.disableHtmlEscaping().create()
output is :
2022-03-28 11:20:06.930 INFO 11920 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2022-03-28 11:20:06.980 INFO 11920 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-03-28 11:20:06.980 INFO 11920 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1290 ms
spring.gson.disable-html-escaping : false
converter.getGson().htmlSafe() : true
2022-03-28 11:20:07.730 INFO 11920 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-03-28 11:20:07.735 INFO 11920 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 13 endpoint(s) beneath base path '/actuator'
2022-03-28 11:20:07.774 INFO 11920 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-28 11:20:07.789 INFO 11920 --- [ restartedMain] com.example.demo.DemoApplication : Started DemoApplication in 2.566 seconds (JVM running for 2.965)
the expected output is :
converter.getGson().htmlSafe() is should return false if
This webapp is going to work with database, but for now I've started with an easiest stub and got stuck.
I'm kinda clueless what is wrong. Overall I'm not that familiar with Spring or with how to understand and trace such errors. The only thing I understand here is that it has nothing to do with the type of a method argument. I've googled this error, looked into some answers about this kind of error here, but failed at finding the right solution.
So, I'm getting this:
:: Spring Boot :: (v2.2.5.RELEASE)
2020-05-22 15:44:36.132 INFO 17992 --- [ main] c.rinkashikachi.SpringReactApplication : Starting SpringReactApplication v0.0.1-SNAPSHOT on DESKTOP-3BPPMPQ with PID 17992 (D:\Projects\J
ava\zni\target\zni-0.0.1-SNAPSHOT.jar started by 15rin in D:\Projects\Java\zni)
2020-05-22 15:44:36.135 INFO 17992 --- [ main] c.rinkashikachi.SpringReactApplication : No active profile set, falling back to default profiles: default
2020-05-22 15:44:37.108 INFO 17992 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-05-22 15:44:37.116 INFO 17992 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-22 15:44:37.116 INFO 17992 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-05-22 15:44:37.166 INFO 17992 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-22 15:44:37.166 INFO 17992 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 999 ms
2020-05-22 15:44:37.241 WARN 17992 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springfram
ework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'utilController' defined in URL [jar:file:/D:/Projects/Java/zni/target/zni-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/co
m/rinkashikachi/controllers/UtilController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyExcep
tion: Error creating bean with name 'databaseMetaDataService': Unsatisfied dependency expressed through method 'getTableListBySchema' parameter 0; nested exception is org.springframework.beans.fact
ory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-05-22 15:44:37.244 INFO 17992 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-05-22 15:44:37.252 INFO 17992 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-22 15:44:37.326 ERROR 17992 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method getTableListBySchema in com.rinkashikachi.service.DatabaseMetaDataService required a bean of type 'java.lang.String' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.
This is where the method is.
package com.rinkashikachi.service;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.repositories.ColNameEntity;
import com.rinkashikachi.service.repositories.TableNameEntity;
import java.util.ArrayList;
import java.util.List;
#Service("databaseMetaDataService")
public class DatabaseMetaDataService {
#Autowired
public List<TableNameEntity> getTableListBySchema(String schema) {
// Stub
List<TableNameEntity> names = new ArrayList<>(3);
switch(schema) {
case "ADDITIONAL":
names.add(new TableNameEntity(1L, "ADDITIONAL1"));
names.add(new TableNameEntity(2L, "ADDITIONAL2"));
names.add(new TableNameEntity(3L, "ADDITIONAL3"));
break;
case "BOOKKEEPING":
names.add(new TableNameEntity(1L, "BOOKKEEPING1"));
names.add(new TableNameEntity(2L, "BOOKKEEPING2"));
names.add(new TableNameEntity(3L, "BOOKKEEPING3"));
break;
}
return names;
}
}
And this is where I use it:
package com.rinkashikachi.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.DatabaseMetaDataService;
import com.rinkashikachi.service.repositories.TableNameEntity;
#Controller
#RequestMapping(value="/api")
public class UtilController {
private final DatabaseMetaDataService databaseMetaDataService;
#Autowired
public UtilController(DatabaseMetaDataService databaseMetaDataService) {
this.databaseMetaDataService = databaseMetaDataService;
}
#GetMapping(value="/tech")
public ResponseEntity<List<String>> getTechData(
#RequestParam(value="schema") String schema,
#RequestParam(value="table", required = false) String table,
#RequestParam(value="column", required = false) String column) {
List<TableNameEntity> entityList = databaseMetaDataService.getTableListBySchema(schema);
List<String> tables = new ArrayList<>(entityList.size());
for (TableNameEntity entity : entityList) {
tables.add(entity.toString());
System.out.println(entity);
}
return !tables.isEmpty()
? new ResponseEntity<>(tables, HttpStatus.OK)
: new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
The problem is with this code:
#Autowired
public List getTableListBySchema(String schema) {
Can you try:
package com.rinkashikachi.service;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.repositories.ColNameEntity;
import com.rinkashikachi.service.repositories.TableNameEntity;
import java.util.ArrayList;
import java.util.List;
#Service("databaseMetaDataService")
public class DatabaseMetaDataService {
public List<TableNameEntity> getTableListBySchema(String schema) {
// Stub
List<TableNameEntity> names = new ArrayList<>(3);
switch(schema) {
case "ADDITIONAL":
names.add(new TableNameEntity(1L, "ADDITIONAL1"));
names.add(new TableNameEntity(2L, "ADDITIONAL2"));
names.add(new TableNameEntity(3L, "ADDITIONAL3"));
break;
case "BOOKKEEPING":
names.add(new TableNameEntity(1L, "BOOKKEEPING1"));
names.add(new TableNameEntity(2L, "BOOKKEEPING2"));
names.add(new TableNameEntity(3L, "BOOKKEEPING3"));
break;
}
return names;
}
}
package com.rinkashikachi.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.DatabaseMetaDataService;
import com.rinkashikachi.service.repositories.TableNameEntity;
#Controller
#RequestMapping(value="/api")
public class UtilController {
#Autowired
private DatabaseMetaDataService databaseMetaDataService;
#GetMapping(value="/tech")
public ResponseEntity<List<String>> getTechData(
#RequestParam(value="schema") String schema,
#RequestParam(value="table", required = false) String table,
#RequestParam(value="column", required = false) String column) {
List<TableNameEntity> entityList = databaseMetaDataService.getTableListBySchema(schema);
List<String> tables = new ArrayList<>(entityList.size());
for (TableNameEntity entity : entityList) {
tables.add(entity.toString());
System.out.println(entity);
}
return !tables.isEmpty()
? new ResponseEntity<>(tables, HttpStatus.OK)
: new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
Marking the getTableListBySchema method as Autowired tells spring to do the dependency injection here. That is why Spring looks for a bean of type Spring to autowire it to the method argument. Remove the Autowired annotation from that method.
As a side-note, if you are developing an api. You should be using the #RestController not #Controller
I have a very simple Spring Boot app that I'm trying to get working with some externalised configuration. I've tried to follow the information on the spring boot documentation however I'm hitting a road block.
When I run the app below the external configuration in the application.properties file does not get populated into the variable within the bean. I'm sure I'm doing something stupid, thanks for any suggestions.
MyBean.java (located in /src/main/java/foo/bar/)
package foo.bar;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
public MyBean() {
System.out.println("================== " + prop + "================== ");
}
}
Application.java (located in /src/main/java/foo/)
package foo;
import foo.bar.MyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
#Autowired
private MyBean myBean;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties (located in /src/main/resources/)
some.prop=aabbcc
Log output when executing the Spring Boot app:
grb-macbook-pro:properties-test-app grahamrb$ java -jar ./build/libs/properties-test-app-0.1.0.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.1.5.RELEASE)
2014-09-10 21:28:42.149 INFO 16554 --- [ main] foo.Application : Starting Application on grb-macbook-pro.local with PID 16554 (/Users/grahamrb/Dropbox/dev-projects/spring-apps/properties-test-app/build/libs/properties-test-app-0.1.0.jar started by grahamrb in /Users/grahamrb/Dropbox/dev-projects/spring-apps/properties-test-app)
2014-09-10 21:28:42.196 INFO 16554 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#67e38ec8: startup date [Wed Sep 10 21:28:42 EST 2014]; root of context hierarchy
2014-09-10 21:28:42.828 INFO 16554 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2014-09-10 21:28:43.592 INFO 16554 --- [ main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-09-10 21:28:43.784 INFO 16554 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2014-09-10 21:28:43.785 INFO 16554 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.54
2014-09-10 21:28:43.889 INFO 16554 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2014-09-10 21:28:43.889 INFO 16554 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1695 ms
2014-09-10 21:28:44.391 INFO 16554 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2014-09-10 21:28:44.393 INFO 16554 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
================== null==================
2014-09-10 21:28:44.606 INFO 16554 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.679 INFO 16554 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2014-09-10 21:28:44.679 INFO 16554 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2014-09-10 21:28:44.716 INFO 16554 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.716 INFO 16554 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.902 INFO 16554 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-09-10 21:28:44.963 INFO 16554 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http
2014-09-10 21:28:44.965 INFO 16554 --- [ main] foo.Application : Started Application in 3.316 seconds (JVM running for 3.822)
^C2014-09-10 21:28:54.223 INFO 16554 --- [ Thread-2] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#67e38ec8: startup date [Wed Sep 10 21:28:42 EST 2014]; root of context hierarchy
2014-09-10 21:28:54.225 INFO 16554 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.
You need to do one of the following:
Better solution
#Component
public class MyBean {
private final String prop;
#Autowired
public MyBean(#Value("${some.prop}") String prop) {
this.prop = prop;
System.out.println("================== " + prop + "================== ");
}
}
Solution that will work but is less testable and slightly less readable
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
public MyBean() {
}
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Also note that is not Spring Boot specific but applies to any Spring application
The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.
Your current way(#grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.
This answer may or may not be applicable to your case ... Once I had a similar symptom and I double checked my code many times and all looked good but the #Value setting was still not taking effect. And then after doing File > Invalidate Cache / Restart with my IntelliJ (my IDE), the problem went away ...
This is very easy to try so may be worth a shot
Actually, For me below works fine.
#Component
public class MyBean {
public static String prop;
#Value("${some.prop}")
public void setProp(String prop) {
this.prop= prop;
}
public MyBean() {
}
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Now whereever i want, just invoke
MyBean.prop
it will return value.
Moved no argument constructor code to PostConstruct has done the trick
for me. As it'll keep default bean loading workflow intact.
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Using Environment class we can get application. Properties values
#Autowired,
private Environment env;
and access using
String password =env.getProperty(your property key);
follow these steps.
1:- create your configuration class like below you can see
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
#Configuration
public class YourConfiguration{
// passing the key which you set in application.properties
#Value("${some.pro}")
private String somePro;
// getting the value from that key which you set in application.properties
#Bean
public String getsomePro() {
return somePro;
}
}
2:- when you have a configuration class then inject in the variable from a configuration where you need.
#Component
public class YourService {
#Autowired
private String getsomePro;
// now you have a value in getsomePro variable automatically.
}
If you're working in a large multi-module project, with several different application.properties files, then try adding your value to the parent project's property file.
If you are unsure which is your parent project, check your project's pom.xml file, for a <parent> tag.
This solved the issue for me.
You can use Environment Class to get data :
#Autowired
private Environment env;
String prop= env.getProperty('some.prop');
Simplest solution that solved this issue for me:
Add #PropertySource annotation to the Component/Service that needs to populate #Value field:
#Service
#PropertySource("classpath:myproperties.properties")
public class MyService {
#Value("${some.prop}")
private String someProperty;
// some logic...
}
Make sure to add the properties file to the resource folder of the same module as your Service/Component.
You are getting this error because you are initializing the class with new keyword. To solve this,
first you need to create the configuration class and under this class you need to create the bean of this class.
When you will call it by using bean then it will work..
package ca.testing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
#Component
#PropertySource("db.properties")
public class ConnectionFactory {
#Value("${jdbc.user}")
private String user;
#Value("${jdbc.password}")
private String password;
#Value("${jdbc.url}")
private String url;
Connection connection;
public Connection getConnection(){
try {
connection = DriverManager.getConnection(url, user, password);
System.out.println(connection.hashCode());
}catch (Exception e){
System.out.println(e);
}
return connection;
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(Config.class);
ConnectionFactory connectionFactory= context.getBean(ConnectionFactory.class);
connectionFactory.getConnection();
}
}
My application properties are picking after i have removed key word new from different class like (new Bean())