I defined the mapper but Spring Boot can't detect it. I couldn't find the problem for days. Please help. Tried on IDEA and Netbeans. Tried to add some annotations on main class from this thread.
Description:
Parameter 1 of constructor in
com.example.springmysqlelastic.service.impl.UserService required a
bean of type 'com.example.springmysqlelastic.mapper.UserMapper' that
could not be found.
Action:
Consider defining a bean of type
'com.example.springmysqlelastic.mapper.UserMapper' in your
configuration.
UserMapper.java
package com.example.springmysqlelastic.mapper;
import com.example.springmysqlelastic.model.Food;
import com.example.springmysqlelastic.model.FoodModel;
import com.example.springmysqlelastic.model.User;
import com.example.springmysqlelastic.model.UserModel;
import com.example.springmysqlelastic.model.dto.FoodDTO;
import com.example.springmysqlelastic.model.dto.UserDTO;
import org.mapstruct.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
//#Component
#Mapper(componentModel = "spring")
public interface UserMapper {
UserDTO toUserDTO(User user);
List<UserDTO> toUserDtos(List<User> users);
User toUser(UserDTO userDTO);
List<User> toUsers(List<UserDTO> userDTOS);
UserModel toUserModel(User user);
/*
FoodDTO toFoodDTO(Food food);
List<FoodDTO> toFoodDtos(List<Food> foods);
Food toFood(FoodDTO foodDTO);
List<Food> toFoods(List<FoodDTO> foodDTOS);
FoodModel toFoodModel(Food food);*/
}
UserService
package com.example.springmysqlelastic.service.impl;
import com.example.springmysqlelastic.mapper.UserMapper;
import com.example.springmysqlelastic.model.User;
import com.example.springmysqlelastic.model.dto.UserDTO;
import com.example.springmysqlelastic.repo.IUserDAO;
import com.example.springmysqlelastic.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService implements IUserService {
private IUserDAO userDAO;
private UserMapper userMapper;
#Autowired
public UserService(IUserDAO userDAO, UserMapper userMapper) {
this.userDAO = userDAO;
this.userMapper = userMapper;
}
#Override
public UserDTO save(UserDTO userDTO) {
User user = this.userDAO.save(this.userMapper.toUser(userDTO));
return this.userMapper.toUserDTO(user);
}
#Override
public UserDTO findById(Long id) {
return this.userMapper.toUserDTO(this.userDAO.findById(id).orElse(null));
}
#Override
public List<UserDTO> findAll() {
return this.userMapper.toUserDtos(this.userDAO.findAll());
}
}
UserController.java
package com.example.springmysqlelastic.rest;
import com.example.springmysqlelastic.model.dto.UserDTO;
import com.example.springmysqlelastic.service.IUserService;
import com.example.springmysqlelastic.utils.PathResources;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/user") //PathResources.USER
public class UserController {
private final IUserService userService;
#Autowired
public UserController(IUserService userService) {
this.userService = userService;
}
#PostMapping("/save") //PathResources.SAVE
public ResponseEntity<UserDTO> saveUser(#RequestBody UserDTO userDTO) {
return new ResponseEntity<>(this.userService.save(userDTO), HttpStatus.OK);
}
#GetMapping("/find-one/{id}") //PathResources.FIND_ONE + "/{" + PathResources.ID + "}"
public ResponseEntity<UserDTO> findById(#PathVariable Long id) {
return new ResponseEntity<>(this.userService.findById(id), HttpStatus.OK);
}
#GetMapping("/find-all") //PathResources.FIND_ALL
public ResponseEntity<List<UserDTO>> findById() {
return new ResponseEntity<>(this.userService.findAll(), HttpStatus.OK);
}
}
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.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-mysql-elastic</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mysql-elastic</name>
<description>Demo project for Mysql and ElasticSearch Synchronization in Spring</description>
<properties>
<java.version>1.8</java.version>
<mapstruct.version>1.4.0.Beta3</mapstruct.version>
<org.json.version>20190722</org.json.version>
<swagger.version>2.9.2</swagger.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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${org.json.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<!--<version>1.18.12</version>-->
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>2.0.2</version>
<type>jar</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<mainClass>com.example.springmysqlelastic.SpringMysqlElasticApplication</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
Main class
package com.example.springmysqlelastic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
//#SpringBootApplication(scanBasePackages={"com.example.springmysqlelastic"})
#EnableElasticsearchRepositories("com.example.springmysqlelastic.repo.elastic")
#EnableScheduling
//#ComponentScan(scanBasePackages = {"com.example.springmysqlelastic"})
//#EntityScan("com.example.springmysqlelastic.model")
//#EnableJpaRepositories("com.example.springmysqlelastic")
//#ComponentScan(basePackages = {"com.example.springmysqlelastic"})
//#EnableAutoConfiguration
public class SpringMysqlElasticApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMysqlElasticApplication.class, args);
}
}
In the documentation says that in addition to the main dependency, you need to add annotationProcessor
Example for Gradle:
dependencies {
implementation 'org.mapstruct:mapstruct:1.4.2.Final'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
}
I think its an issue with swagger conflicting with the mapstruct library..
I modified your POM like below and it started working for me. They have some documentation here that talks about it. https://www.programmersought.com/article/6208308983/
<?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.example</groupId>
<artifactId>spring-mysql-elastic</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mysql-elastic</name>
<description>Demo project for Mysql and ElasticSearch Synchronization in Spring</description>
<properties>
<java.version>1.8</java.version>
<mapstruct.version>1.4.0.Beta3</mapstruct.version>
<org.json.version>20190722</org.json.version>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${org.json.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<!--<version>1.18.12</version>-->
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>2.0.2</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.0.Beta3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<mainClass>com.example.springmysqlelastic.SpringMysqlElasticApplication</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.0.Beta3</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
PS: I have removed JPA dependency to make it work without spring. Forget it.
You can find that I have changed swagger dependencies to look like below -
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</exclusion>
</exclusions>
</dependency>
Can you check if it works for you?
Update
After codegen step, this is what it generates -
package com.example.springmysqlelastic.mapper;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import org.springframework.stereotype.Component;
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2020-08-11T16:40:57+0530",
comments = "version: 1.4.0.Beta3, compiler: javac, environment: Java 1.8.0_265 (Private Build)"
)
#Component
public class UserMapperImpl implements UserMapper {
#Override
public UserDTO toUserDTO(User user) {
if ( user == null ) {
return null;
}
UserDTO userDTO = new UserDTO();
return userDTO;
}
#Override
public List<UserDTO> toUserDtos(List<User> users) {
if ( users == null ) {
return null;
}
List<UserDTO> list = new ArrayList<UserDTO>( users.size() );
for ( User user : users ) {
list.add( toUserDTO( user ) );
}
return list;
}
#Override
public User toUser(UserDTO userDTO) {
if ( userDTO == null ) {
return null;
}
User user = new User();
return user;
}
#Override
public List<User> toUsers(List<UserDTO> userDTOS) {
if ( userDTOS == null ) {
return null;
}
List<User> list = new ArrayList<User>( userDTOS.size() );
for ( UserDTO userDTO : userDTOS ) {
list.add( toUser( userDTO ) );
}
return list;
}
}
Related
I encounter a
No qualifying bean of type security.oauth2.client.OAuth2AuthorizedClientService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Don't understand what it expected. It's a dependancy.
Here's the LoginController :
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.security.RolesAllowed;
import java.security.Principal;
import java.util.Map;
#RestController
public class LoginController {
private OAuth2AuthorizedClientService authorizedClientService;
public LoginController(OAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientService = authorizedClientService;
}
#RequestMapping("/**")
#RolesAllowed("USER")
public String getUser(){
return "dashboard";
}
#RequestMapping("/admin")
#RolesAllowed("ADMIN")
public String getAdmin(){
return "Welcome, Admin";
}
#RequestMapping("/*")
public String getUserInfos(Principal activeUser){
StringBuffer userInfos = new StringBuffer();
if (activeUser instanceof UsernamePasswordAuthenticationToken){
userInfos.append(getUsernamePasswordPasswordLoginInfo(activeUser));
} else if (activeUser instanceof OAuth2AuthenticationToken){
userInfos.append(getOAuth2LoginInfo(activeUser));
}
return userInfos.toString();
}
private StringBuffer getOAuth2LoginInfo(Principal activeUser) {
StringBuffer protectedInfo = new StringBuffer();
OAuth2AuthenticationToken authToken = (OAuth2AuthenticationToken) activeUser;
OAuth2User principal = ((OAuth2AuthenticationToken)activeUser).getPrincipal();
OAuth2AuthorizedClient authClient = this.authorizedClientService
.loadAuthorizedClient(authToken.getAuthorizedClientRegistrationId(), authToken.getName());
Map<String, Object> userDetails = ((DefaultOAuth2User) authToken.getPrincipal()).getAttributes();
String userToken = authClient.getAccessToken().getTokenValue();
protectedInfo.append("Welcome, " + userDetails.get("name") + "<br><br>");
protectedInfo.append("email: " + userDetails.get("email") + "<br><br>");
protectedInfo.append("Access Token: " + userToken + "<br><br>");
OidcIdToken idToken = getIdToken(principal);
if(idToken != null){
protectedInfo.append("Token value: " + idToken.getTokenValue() + "<br><br>");
protectedInfo.append("Token mapped values <br><br>");
Map<String, Object> claims = idToken.getClaims();
for (String key : claims.keySet()) {
protectedInfo.append(" " + key + ": " + claims.get(key) + "<br>");
}
}
return protectedInfo;
}
private StringBuffer getUsernamePasswordPasswordLoginInfo(Principal activeUser) {
StringBuffer usernameInfo = new StringBuffer();
UsernamePasswordAuthenticationToken token = ((UsernamePasswordAuthenticationToken) activeUser);
if (token.isAuthenticated()){
User u = (User) token.getPrincipal();
usernameInfo.append("Welcome, " + u.getUsername());
} else {
usernameInfo.append("NA");
}
return usernameInfo;
}
private OidcIdToken getIdToken(OAuth2User principal){
if(principal instanceof DefaultOidcUser) {
DefaultOidcUser oidcUser = (DefaultOidcUser)principal;
return oidcUser.getIdToken();
}
return null;
}
}
Here's the pom.xml... maybe it's a dependancy import problem:
<properties>
<java.version>17</java.version>
<pebble.version>3.1.5</pebble.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>2.6.2</version>
<scope>runtime</scope>
<optional>true</optional>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.1.3</version>
</dependency>
<dependency>
<groupId>io.pebbletemplates</groupId>
<artifactId>pebble-spring-boot-2-starter</artifactId>
<version>3.0.10</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</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>
</plugins>
</build>
Ok.
The problem was the application.properties
The openId was badly configured... it couldn't instanciate the bean... that's what written in the terminal... can't say was crystal clear but was written
Hi I have newly created a microservice post API call with STS4 which was build and deployed successfully. the localhost:8080/demo/ link is opening up. but the rest maping underneath it failing with 404 not found. I haved added requestmapping and post mapping and tried still not working. Can anyone fix the code?
PFB the code:-
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.5.3</version>
<!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<maven.test.skip> true</maven.test.skip>
</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-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
here is the config for swagger :-
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
//Enable Swagger
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
//creating constructor of Docket class that accepts parameter DocumentationType
return new Docket(DocumentationType.SWAGGER_2);
}
}
here is the rest controller:
package com.example.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.MyResponse;
import com.example.demo.service.dao.DemoServiceDAO;
import com.example.demo.service.impl.DemoServiceImpl;
#RestController
#Validated
#RequestMapping(value ="/newcall", method = RequestMethod.POST)
public class DemoController {
Logger logger =LoggerFactory.getLogger(DemoController.class);
#PostMapping(value ="/newResp", headers ="Accept=Application/JSON", produces="Application/JSON")
public MyResponse newResp(#RequestBody String myInput) {
MyResponse myResponse = null;
try {
DemoServiceDAO demoServiceDAO = new DemoServiceImpl();
logger.debug("Started getValue() method...");
myResponse=demoServiceDAO.getValue(myInput);
logger.debug("Completed getValue() method...");
}
catch(Exception e){
logger.debug("Exception occurs",e);
e.printStackTrace();
System.out.println("Exception occurs");
}
return myResponse;
}
}
here is the application:-
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#SpringBootApplication
#ComponentScan(basePackages = "com.example.*")
#EnableSwagger2
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
Logger logger =LoggerFactory.getLogger(DemoApplication.class);
SpringApplication.run(DemoApplication.class, args);
}
}
here is the app.properties:-
logging.file.name=opt/var/logs/demoService.log
logging.file.path=opt/var/logs
logging.level.web=DEBUG
spring.jmx.default-domain=demo
server.servlet.context-path=/demo
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
springfox.documentation.swagger-ui.base-url=true
management.endpoint.info.enabled: true
springfox.documentation.swagger-ui.enabled=true
springfox.documentation.open-api.enabled=true
spring.security.user.name = user
spring.security.user.password = password
Output from http://localhost:8080/demo/
"_links" : {
"profile" : {
"href" : "http://localhost:8080/demo/profile"
}
}
full code is in github with logs:-
https://github.com/Sourav654/tempProject/tree/master/demo
Without any logs we can only guess, but looking at your Controller I see some weird things. Can you please try the following?
#RestController
#Validated
#RequestMapping("newcall")
public class DemoController {
Logger logger =LoggerFactory.getLogger(DemoController.class);
#PostMapping("/newResp", consumes = "application/json", produces = application/json)
public MyResponse newResp(#RequestBody String myInput) {
MyResponse myResponse = null;
try {
DemoServiceDAO demoServiceDAO = new DemoServiceImpl();
logger.debug("Started getValue() method...");
myResponse=demoServiceDAO.getValue(myInput);
logger.debug("Completed getValue() method...");
}
catch(Exception e){
logger.debug("Exception occurs",e);
e.printStackTrace();
System.out.println("Exception occurs");
}
return myResponse;
}
}
I have a question about Cucumber library, I was taking a course of selenium with cucumber and testNg, but I have run into some problems because some methods no longer exist
For Example:
I cant used "CucumberFeatureWrapper" what could be the relative to this? Image: https://i.stack.imgur.com/3JMcD.png
The same way happens when i need to used .provideFeatures(); in testNgCucumberRunner.provideFeatures Image: https://i.stack.imgur.com/L76xQ.png
POM:
e<?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>groupId</groupId>
<artifactId>CRMFramework</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>10</source>
<target>10</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
<suiteXmlFiles>
<suiteXmlFile>src/test/java/TestNg.xml</suiteXmlFile>
</suiteXmlFiles>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>net.masterthought</groupId>
<artifactId>maven-cucumber-reporting</artifactId>
<version>5.4.0</version>
<executions>
<execution>
<id>execution</id>
<phase>verify</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<projectName>ExecuteAutomation</projectName>
<!-- output directory for the generated report -->
<outputDirectory>${project.build.directory}/cucumber-reports</outputDirectory>
<inputDirectory>${project.build.directory}/cucumber-json-report.json</inputDirectory>
<jsonFiles>
<!-- supports wildcard or name pattern -->
<param>**/*.json</param>
</jsonFiles>
<mergeFeaturesWithRetest>true</mergeFeaturesWithRetest>
<mergeFeaturesById>true</mergeFeaturesById>
<checkBuildResult>false</checkBuildResult>
<skipEmptyJSONFiles>true</skipEmptyJSONFiles>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>6.9.1</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-core</artifactId>
<version>6.9.1</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>6.9.1</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>6.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/datatable-dependencies -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>datatable-dependencies</artifactId>
<version>1.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.0.6</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
TestRunner
import com.aventstack.extentreports.gherkin.model.Feature;
import com.crm.framework.utilities.ExtentReport;
import io.cucumber.testng.*;
import org.testng.annotations.Test;
import org.testng.ITestContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import java.util.List;
//json:target/cucumber-reports/cucumberTestReport.json
#CucumberOptions(
features = {"src/test/java/features/"},
glue = {"steps"},
plugin = {"json:target/cucumber-json-report.json",
"pretty", "html:target/cucumber-report-html"})
public class TestRunner {
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test(dataProvider = "features")
public void LoginTest(CucumberFeatureWrapper cucumberFeatureWrapper) throws ClassNotFoundException {
//Insert the Feature Name
//ExtentReport.startFeature("login").assignAuthor("DiegoHM").assignDevice("Chrome").assignCategory("Regression");
}
#DataProvider
public Object[] features(ITestContext context) {
// return testNGCucumberRunner.
return testNGCucumberRunner.provideFeatures();
}
#AfterClass(alwaysRun = true)
public void afterClass() {
testNGCucumberRunner.finish();
}
}
You're using classes that don't exist anymore. You can find out which classes are in a library by using ctrl/cmd + clicking on a package name in most modern IDEs.
So try using:
package io.cucumber.examples.testng;
import io.cucumber.testng.CucumberOptions;
import io.cucumber.testng.FeatureWrapper;
import io.cucumber.testng.PickleWrapper;
import io.cucumber.testng.TestNGCucumberRunner;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
#CucumberOptions(....)
public class RunCucumberByCompositionTest {
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test(groups = "cucumber", description = "Runs Cucumber Scenarios", dataProvider = "scenarios")
public void scenario(PickleWrapper pickle, FeatureWrapper cucumberFeature) {
testNGCucumberRunner.runScenario(pickle.getPickle());
}
#DataProvider
public Object[][] scenarios() {
return testNGCucumberRunner.provideScenarios();
}
#AfterClass(alwaysRun = true)
public void tearDownClass() {
testNGCucumberRunner.finish();
}
}
From:
https://github.com/cucumber/cucumber-jvm/blob/main/examples/java-calculator-testng/src/test/java/io/cucumber/examples/testng
I have a Jersey Rest Web Service and I would like to send json response removing all fields with null values from json response.
I'm using
#JsonInclude(JsonInclude.Include.NON_NULL)
but it doesn't work at both class and attribute level.
My resource class contain this function:
#RolesAllowed("ADMIN")
#Path("/test")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#ApiOperation(value = "test Create", response = TestResponse.class)
public Response Create(TestRequest request, #Context ContainerRequestContext context) {
TestResponse resp = new TestResponse();
resp.setValueA("Value A");
return Response.ok().entity(resp).build();
}
TestResponse class contain:
#ApiModel("TestResponse")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class TestResponse{
#JsonProperty
private String valueA;
#JsonProperty
private String valueB;
#ApiModelProperty(value = "Value A", example = "value A")
public String getValueA(){
return valueA;
}
public SetValueA(String valueA){
this.valueA = valueA;
}
#ApiModelProperty(value = "Value B", example = "value B")
public String getValueB(){
return valueB;
}
public SetValueB(String valueB){
this.valueB = valueB;
}
}
my JSON response contain:
{"valueA":"ValueA","valueB":null}
but I would like to send back this JSON:
{"valueA":"ValueA"}
this is my application class:
#ApplicationPath("/rest")
public class App extends ResourceConfig {
public App() {
packages("it.ivan");
// Register Auth Filter here
register(AuthenticationFilter.class);
register(StartupHandler.class);
register(MultiPartFeature.class);
register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000));
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("Ivan Rest Application");
beanConfig.setVersion("1.0.0");
beanConfig.setBasePath("/rest/");
beanConfig.setResourcePackage("it.ivan");
beanConfig.setScan(true);
register(beanConfig);
register(io.swagger.jaxrs.listing.ApiListingResource.class);
register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
register(io.swagger.jaxrs.config.DefaultJaxrsConfig.class);
Swagger swagger = new Swagger();
swagger.securityDefinition("basicAuth", new BasicAuthDefinition());
new SwaggerContextService().updateSwagger(swagger);
}
}
this is my pom.xml file:
<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>it.ivan</groupId>
<artifactId>TestRest</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>TestRest</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jersey.version>2.33</jersey.version>
<slf4j.version>1.7.29</slf4j.version>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20201115</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
UPDATE... ISSUE SOLVED...
I removed this dependecy:
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
and I added this one:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
I'm new to Spring and I'm getting the error below when I try to run my application. Am I missing any Spring annotation?
Should I create a JpaUpdateRepositoryImpl class instead?
APPLICATION FAILED TO START
Description:
Parameter 1 of constructor in com.myapp.domain.service.StoreAsyncService required a bean of type 'com.myapp.domain.repository.JpaUpdateRepository' that could not be found.
Action:
Consider defining a bean of type 'com.myapp.domain.repository.JpaUpdateRepository' in your configuration.
Service Class
package com.myapp.domain.service;
import com.myapp.domain.model.Store;
import com.myapp.domain.repository.JpaUpdateRepository;
import com.myapp.facade.ElasticSearchFacade;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
#Async
#Service
public class StoreAsyncService {
static Logger logger = LoggerFactory.getLogger(StoreAsyncService.class);
private Integer partitionSize = 1000;
private Integer parallelism = 4;
private final ElasticSearchFacade elasticSearch;
private final JpaUpdateRepository repository;
public StoreAsyncService(ElasticSearchFacade elasticSearch, JpaUpdateRepository repository) {
this.elasticSearch = elasticSearch;
this.repository = repository;
}
public void exportStores(List<Store> stores) {
List<List<Store>> storesSubset = Lists.partition(stores, partitionSize);
ForkJoinPool pool = new ForkJoinPool(parallelism);
for (List<Store> storesItem : storesSubset) {
CompletableFuture.runAsync(() -> sendToElastic(storesItem), pool);
}
pool.shutdown();
LocalDateTime localDateTime = LocalDateTime.now();
repository.updateCadConfiguracaoWithLastExecutionDate(localDateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
}
public void sendToElastic(List<Store> stores) {
elasticSearch.post(stores);
logger.info("sentToElastic - {} Stores sent to Elastic", stores.size());
}
}
Repository
package bcom.myapp.domain.repository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface JpaUpdateRepository extends CrudRepository<Object, Integer> {
#Modifying
#Query("UPDATE CONFIG c SET c.VALOR = :lastExecutionDate WHERE c.CODE = 'EXPORTACAO_WORKER_STORE' ")
void updateCadConfiguracaoWithLastExecutionDate(#Param("lastExecutionDate") String lastExecutionDate);
}
POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>br.com.getnet</groupId>
<artifactId>cstores-worker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tores-worker</name>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</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>
<version>2.3.1.RELEASE</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.7.RELEASE</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3.0.0</version><!--$NO-MVN-MAN-VER$-->
<exclusions>
<exclusion>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>simplefan</artifactId>
</exclusion>
<exclusion>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ons</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.10.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>4.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Configuration
package com.myapp.infrastructure.config;
import org.apache.http.HttpHost;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import static org.apache.http.auth.AuthScope.ANY;
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.myapp.infrastructure")
#ComponentScan(basePackages = {"com.myapp.domain"})
public class ElasticSearchConfig {
#Value("${app.url}")
String elasticPostUrl;
#Value("${app.port}")
Integer elasticPostPort;
#Value("${app.username}")
String userName;
#Value("${app.password}")
String userPassword;
BasicCredentialsProvider credentialsProvider;
#Bean
public RestHighLevelClient client() {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, userPassword);
this.credentialsProvider = new BasicCredentialsProvider();
this.credentialsProvider.setCredentials(ANY, credentials);
HttpHost httpHost = new HttpHost(elasticPostUrl, elasticPostPort, "http");
RestClientBuilder builder = RestClient.builder(httpHost)
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultCredentialsProvider(
this.credentialsProvider));
return new RestHighLevelClient(builder);
}
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchRestTemplate(client());
}
}
You need to use #EnableAsync on the class level instead of #Async and use #Async on the Methods that shall run asynchronously, As the #EnableAsync annotation applied on application classes for asynchronous behavior and look for methods marked with #Async annotation and run in background thread pools.
It would be nice to check your imports, package declaration and config java files. Please add them and I will be happy to help.
You can try to set up a scan for your repository in your SpringBoot Main application like:
#EnableJpaRepositories("...your.repository.package.name")