#Validated + javax annotations not working for controller method parameters - spring

I have a Restcontroller in a Spring project. And I have to validate its method's parameter.
Mainly Spring #Validated annotation on class + javax validation annotations are proposed to be a good practice working examples.
But it failed: Spring just ignores this validation: ConstraintViolationException supposed to be thrown is probably smoking somewhere outside and lets other exceptions do the dirty work following the code.
#RestController
#RequiredArgsConstructor
#RequestMapping("/reducedPageNumbers")
#Validated
#Tag(
name = "Page number reducer controller",
description = "This controller is responsible for the reduction of a given range of page numbers for printer"
)
public class PageReducerController {
private final PageReducerService service;
#Operation(
method = "GET",
summary = "Finding a user by ID",
responses = {
#ApiResponse(responseCode = "200", description = "Successful Request"),
#ApiResponse(responseCode = "400", description = "Bad Request. " +
"All page numbers must be integers, separated by comas", content = {
#Content(
mediaType = "application/json",
array = #ArraySchema(schema = #Schema(implementation = ErrorContainer.class)))
}),
#ApiResponse(responseCode = "500", description = "Unexpected Internal Server Error", content =
#Content)
},
description = "This method transforms a list of page numbers in one String line, separated by ',' " +
"into ascending reduced format of a String line for printer. " +
"E.g.: \"1,3,32,5,11,7,6,19,2,21,4,8,22,23\" -> \"1-8,11,19,21-23,32\". " +
"And returns a ReducerResponse object with both initial String input line 'original' " +
"and reduced String line 'reduced'"
)
#GetMapping
public ResponseEntity<ReducerResponse> show(#NotNull #NotBlank String rawPageNumbers) {
ReducerResponse response = service.reduce(rawPageNumbers);
return new ResponseEntity<>(response, HttpStatus.OK);
}
What can be a problem here?
Tried to validate a method parameter through #Validated + javax validation annotations. Expected: ConstraintViolationException. Actually resulted: validation totally ignored.
I also made sure I use spring validation starter, hibernate-validator 6.0.0 and configured MethodValidationPostProcessor as follows:
#Configuration
public class ValidationConfig {
#Bean
public MethodValidationPostProcessor getMethodValidationPostProcessor(){
MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
processor.setValidator(this.validator());
return processor;
}
#Bean
public LocalValidatorFactoryBean validator(){
return new LocalValidatorFactoryBean();
}
}
My Pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.8</version>
<relativePath/>
</parent>
<groupId>by.smirnov</groupId>
<artifactId>pagenumberreducer</artifactId>
<version>1.0.1</version>
<name>pagenumberreducer</name>
<description>Page number reducer test project</description>
<properties>
<java.version>11</java.version>
<springdoc.version>1.6.14</springdoc.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.0.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

It started to work properly on Boot 3 with Jakarta 3.

Related

Tomcat redirects all post request to get

I have issue with tomcat 9.0.50.
I have a basic Springboot application to deploy and all my post requests are actually redirected to GET request.
here is my Main class:
#SpringBootApplication
public class WsApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(WsApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WsApplication.class);
}
}
Here i simply extend my class with SpringBootServletInitializer and I added the configure method.
Second point: I created a GET and a POST request in a controller.
#RestController
#RequestMapping("/")
public class AppController {
#GetMapping
public String hello() {
return "Hello";
}
#PostMapping
public String helloName(#RequestBody String name) {
return "Hello " + name;
}
}
I also have my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>ws-application</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ws-facturx</name>
<description>ws-facturx</description>
<packaging>war</packaging>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
In my application.prpperties I configured SQL and application name:
# ws-application
spring.application.name=ws-application
# postgresql
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL81Dialect
It should normally work correctly. I can send GET request to my base URL and do retrieve the expected response. When I send a POST request, i obtain a 302 response. I created a dummy application to check if issue was coming from the application.
I tried the call using postman and with a curl request:
curl -i -X POST -H "Content-Type: text/plain" -d "John" http://localhost:8080/ws-application
Is there any issue with tomcat or Springboot ? The java version used is provided in jdk-11.0.6
I don't really know "why" I have been able to solve this issue but here is the "how".
#Slf4j
#RestController
#RequestMapping("/api")
public class FacturxController {
#GetMapping
public String hello() {
return "Hello";
}
#PostMapping
public String helloName(#RequestBody String name) {
log.info("Hello Name");
return "Hello " + name;
}
}
this app has just one controller, but it seems that it required to set a path to the RequestMapping.

Repository bean cannot be found (No idea why)

I'm trying to run my application and I'm receiving this error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.danielturato.product.services.ProductServiceImpl required
a bean of type 'com.danielturato.product.persistence.ProductRepository' that could not be
found.
Action:
Consider defining a bean of type 'com.danielturato.product.persistence.ProductRepository' in
your configuration.
I have no idea why this is occurring. I've tried to look at past solutions where its said to use the #EnableMongoRepository to point to the correct package however I have tried this and it doesn't work. I've also tried adding the #Repository annotation above my repository (even though its not needed) and it doesn't work still. Here is my code for my repository, application & where the repository is failing to be injected.
Application:
#SpringBootApplication
#ComponentScan("com.danielturato")
public class ProductServiceApplication {
private static final Logger LOG = LoggerFactory.getLogger(ProductServiceApplication.class);
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}
Repository:
public interface ProductRepository extends ReactiveCrudRepository<ProductEntity, String> {
Mono<ProductEntity> findByProductId(int productId);
}
ProductServiceImpl:
#RestController
public class ProductServiceImpl implements ProductService {
private static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class);
private final ServiceUtil serviceUtil;
private final ProductRepository repository;
private final ProductMapper mapper;
#Autowired
public ProductServiceImpl(ProductRepository repository, ProductMapper mapper, ServiceUtil serviceUtil) {
this.repository = repository;
this.mapper = mapper;
this.serviceUtil = serviceUtil;
}
Pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.danielturato</groupId>
<artifactId>product-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>product-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.danielturato</groupId>
<artifactId>api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.danielturato</groupId>
<artifactId>util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Beta2</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
If anyone can suggest for me anything to try or would like me to put more info here please let me know.
The stack trace you have included in your question does point to the ProductRepository not being available for autowiring and as a previous comment has pointed out this is because you are missing the #Repository annotation from your repository.
Another reason is if your repository cannot find a matching entity. This might be for example if the Id is the wrong type or is missing the #Id annotation, if the entity doesn't have either #Entity/#Document or if it is missing an all args constructor. Plus in your case you have added a findByProductId() method so your entity will need a productId field too.
I would also remove the #ComponentScan annoatation from your application class as this is included by default in #SpringBootApplication unless you are intentionally pointing it at a different class path.
If this still fails as you have mentioned in your comments is it failing for the same reason or is there a different error now related to ProductMapper or ServiceUtil?

jackson-data-format doesn't convert when using with restTemplate getforObject()

This question is related to [Rest template getForObject() mapping only camel case fields
Having a rest web service that returns the below xml response.
<Person>
<ttId>1408</ttId>
<FirstName>RAJ</FirstName>
<NationalityValue>INDIAN</NationalityValue>
<Sex>Male</Sex>
</Person>
This is the dto
import java.io.Serializable;
import java.util.Date;
public class PersonInfoDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long ttId;
private String NationalityValue;
private String Sex;
private String FirstName;
//getters and setters
}
Using Spring Boot, When I try to consume using code it returns only one value(which is in camel case). Do I need to add any Naming strategy to make it work ?
String uri = apiPath;
RestTemplate restTemplate = new RestTemplate();
PersonInfoDto personInfoDto = restTemplate.getForObject(uri, PersonInfoDto.class);
//Here the object will contain only one value
ttId = 1408
rest values are returns null.
This is pom file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>msa</groupId>
<artifactId>MQA</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>MQA</name>
<description>MQA project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<orika-core.version>1.4.6</orika-core.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- Oracle JDBC driver -->
<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc14 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Orika -->
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>${orika-core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When I removed the below entry from it worked.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
But to map the RequestBody with XML data this dependency is required.
How can I solve this, which converter does rest template is using ? Can I force rest template to use a particular converter. ?
Hi Try adding #XmlRootElement on the PersonInfoDto class. And try once in web browser giving the URI which you are passing.

Spring Boot Actuator 2.x #WriteOperation with an object as parameter

What I try to achieve:
I want to create an endpoint that is accessible from web and jmx with an action that takes an object as a parameter
here is a simple example:
pom.xml
....
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
The Object class:
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Dog {
protected String name;
protected int age;
}
The endpoint class
#Component
#Endpoint(id = "dogs")
#Slf4j
public class EndpointDogsExperiment {
protected List<Dog> dogs = new ArrayList<>();
public EndpointDogsExperiment() {
dogs.add(new Dog("dog0", 5));
dogs.add(new Dog("dog1", 7));
log.debug("dogs created {}", dogs.toString());
}
#WriteOperation
public List<Dog> addDog(Dog dog) {
log.debug("adding a dog \n{}", dog );
dogs.add(dog);
return dogs;
}
}
the problem:
how do I "call" this operation
when I try HTTP POST with
/actuator/dogs
and body
{"dog":{"name":"aaaa", "age":33}}
client gets
Response:
status: 400
date: Sat, 31 Mar 2018 14:59:41 GMT
connection: close
transfer-encoding: chunked
content-type: application/vnd.spring-boot.actuator.v2+json;charset=UTF-8
{"timestamp":"2018-03-31T14:59:41.778+0000","status":400,"error":"Bad Request","message":"No message available","path":"/actuator/dogs"}
and server log say
2018-03-31 17:59:41.766 WARN 12828 --- [nio-8081-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 8] (through reference chain: java.util.LinkedHashMap["dog"])
I have tried to create a #WriteOperation that has a String parameter and then
HTTP POST body
{"paramName":"StringParamValue"}
works ok
why is it?
Thanks!
Endpoint operations don’t support complex input such as your Dog type. You could, however, consume separate name and age parameters and create the Dog in the operation’s implementation:
#WriteOperation
public List<Dog> addDog(String name, int age) {
Dog dog = new Dog(name, age);
log.debug("adding a dog \n{}", dog );
dogs.add(dog);
return dogs;
}
You can learn more in Spring Boot's reference documentation.
Just use the #RestControllerEndpoint(id = "features") class level annotation.
On the methods you then have to use your regular #PostMapping annotation and it should work

Getting error running spring boot application using -jar

This question has been asked over and over, however I couldn't find my answer. I have an application using spring boot, which intellij can run it without any issue, however java -jar echohostname.jar give me this error:
Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
Here is my Main class:
public class ApplicationMain {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringConfiguration.class);
ConfigurableApplicationContext applicationContext = builder.run(args);
}
This is my Controller class:
#RestController
public class Controller {
#Autowired
#Qualifier("getSigarProxy")
private SigarProxy sigarProxy;
#RequestMapping(value = "/hostname", method = RequestMethod.GET)
public String hostName() throws SigarException {
return "HELLO THERE";
//return sigarProxy.getNetInfo().getHostName();
}
}
And this is spring configuration class:
#SpringBootApplication
#Configuration
#ComponentScan("controller")
public class SpringConfiguration {
#Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public Sigar getSigar() {
return new Sigar();
}
#Bean
public SigarProxy getSigarProxy() {
return SigarProxyCache.newInstance(getSigar(), 1000);
}
#Bean
#Scope("prototype")
public HttpHeaders getHttpHeaders() {
return new HttpHeaders();
}
#Bean
#Scope("prototype")
public AsyncRestTemplate getRestTemplate() {
return new AsyncRestTemplate();
}
}
POM file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>echoHostname</groupId>
<artifactId>echoHostname</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
</dependencies>
</project>
UPDATED MAIN:
public class ApplicationMain {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SpringConfiguration.class, args);
}
}
UPDATED POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>echoHostname</groupId>
<artifactId>echoHostname</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.2.7.RELEASE</version>
</dependency>
</dependencies>
</project>
Any help is appreciated.
Add class level #SpringBootApplication annotation in ApplicationMain.java
Add the below plugin in your pom.xml. Build the maven project and execute the jar command
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
This page has more information on maven assembly plugin - https://maven.apache.org/plugins/maven-assembly-plugin/usage.html
In a spring-boot project, you need that the parent pom be
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
You can remove the spring dependencies, like context, core and beans.
Add to the pom
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
And build the jar again.

Resources