org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class - spring

In my microservice Spring Boot application i added Swagger for my REST api's documentation. Before that my Spring Boot microservice was started fine. But When I add my add my SwaggerConfig the project can't start. I had this error :
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.myproject.MyApplication]; nested exception is java.io.FileNotFoundException: class path resource [springfox/bean/validators/configuration/BeanValidatorPluginsConfiguration.class] cannot be opened because it does not exist
The SwaggerConfig is in common project that add to dependency into my microservice pom.
This my project configuration
SwaggerConfig
package com.project.common.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
#Configuration
#EnableSwagger2
#Import({ BeanValidatorPluginsConfiguration.class })
public class SwaggerConfig {
#Value("${swagger.api.title: no title}")
private String title;
#Value("${swagger.api.package}")
private String apipackage;
#Value("${swagger.api.version:no version}")
private String version;
#Value("${swagger.api.description:no description}")
private String description;
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage(apipackage))
.paths(PathSelectors.any()).build().useDefaultResponseMessages(false)
.apiInfo(new ApiInfoBuilder().title(title).description(description)
.version(version).build())
.globalResponseMessage(RequestMethod.GET,defaultResponse())
.globalResponseMessage(RequestMethod.POST,defaultResponse())
.globalResponseMessage(RequestMethod.PUT,defaultResponse())
.globalResponseMessage(RequestMethod.DELETE,defaultResponse());
}
private static List<ResponseMessage> defaultResponse(){
return
List.of(new ResponseMessageBuilder().code(500).message("Internal server error").build(),
new ResponseMessageBuilder().code(400).message("bad request").build(),
new ResponseMessageBuilder().code(404).message("not found").build());
}
}
Main class
package com.project.company;
import com.project.common.config.SwaggerConfig;
import com.project.company.infrastructure.config.MyApplicationConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import java.util.ArrayList;
import java.util.List;
#SpringBootApplication(exclude={SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
#Import({MyApplicationConfig.class, SwaggerConfig.class})
public class MyCompanyApplication {
public static void main(String[] args) {
SpringApplication.run(MyCompanyApplication.class, args);
}
#Bean
public CommandLineRunner init(){
return (String... args)->{
// do something
};
}
}

I found my error. I forgot this dependency :
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
</dependency>

Related

Missing bean in controller even after adding ComponentScan annotation

I am trying to run a spring boot application which gets a list of names of people from the database. I am getting the below error :
Description:
Field peopleserviceinterface in com.sample.lombpackdemo.controller.FriendController required a bean of type 'com.sample.lombpackdemo.service.FriendsServiceInterface' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.sample.lombpackdemo.service.FriendsServiceInterface' in your configuration.
package com.sample.lombpackdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sample.lombpackdemo.entity.Friends;
import com.sample.lombpackdemo.rowmapper.FriendsRowMapper;
import com.sample.lombpackdemo.service.FriendsServiceInterface;
#CrossOrigin(origins = { "http://localhost:3000"})//to allow access from other servers
#RestController
#RequestMapping("/code")
#ComponentScan(basePackages="com.sample.lombpackdemo.service")
public class FriendController {
#Autowired
private FriendsServiceInterface peopleserviceinterface;//autowire the service
#GetMapping("/all")
public ResponseEntity<List<Friends>> getAllPeople(){
List <Friends> listOfAllPpl = peopleserviceinterface.getAllFriends();
System.out.println("Getting all friends"+listOfAllPpl.toString());
return new ResponseEntity<List<Friends>>(listOfAllPpl,HttpStatus.OK);
}
}
The FriendServiceInterface class is as below:
package com.sample.lombpackdemo.service;
import java.util.List;
import org.springframework.stereotype.Component;
import com.sample.lombpackdemo.entity.Friends;
#Component
public interface FriendsServiceInterface {
public List<Friends> getAllFriends();
}
The FriendService class:
package com.sample.lombpackdemo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.sample.lombpackdemo.entity.Friends;
import com.sample.lombpackdemo.repos.FriendsRepo;
import com.sample.lombpackdemo.rowmapper.FriendsRowMapper;
#Service
#Profile("devel")//added to disable CORS only on development time
#Configuration
#Component
public class FriendService implements FriendsServiceInterface {
#Autowired
private FriendsServiceInterface peopleserviceinterface;
#Autowired
private FriendsRepo pplRepo;//should always autowire repository
#Autowired
private JdbcTemplate jdbc;
private static long idCounter = 0;
//FriendsRowMapper fRowMap=new FriendsRowMapper();
#Override
public List<Friends> getAllFriends() {
String sql="select f_name from list_friends";
return jdbc.query(sql, new FriendsRowMapper() );
/*
List<Friends> ppList= (List<Friends>) fRowMap.findAll();
try {
System.out.println("Repository value"+pplRepo.findAll());
System.out.println("Inside findAll of service class" +ppList.toString() );
}
catch(Exception e)
{
}
return ppList;
//
*/}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
//registry.addMapping("/save-javaconfig").allowedOrigins("http://localhost:3000");
}
};
}
Please let me know what else needs to be changed. I have tried adding Component annotation to FriendService class and ComponentScan annotation to the controller class.
Edited to add JdbcConfig class
package com.sample.lombpackdemo.repos;
//import java.util.logging.Logger;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
#Configuration
#ComponentScan(basePackages = "com.sample.lombpackdemo")
public class SpringJdbcConfig {
protected final Logger log = LoggerFactory.getLogger(getClass());
#Bean
public DataSource mysqlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/person_example");
dataSource.setUsername("root");
dataSource.setPassword("subfio");
return dataSource;
}
#Bean(name = "dbProductService")
#ConfigurationProperties (prefix = "spring.datasource")
#Primary public DataSource createProductServiceDataSource()
{ System.out.println("Inside db cofig ");
return DataSourceBuilder.create().build(); }
}
}

Spring Boot #ComponentScan finds candidate component class but does not inject #Configuration beans

I have #SpringBootApplication with #ComponentScan({"myPackage"}) and in myPackage I have a class annotated with #Configuration or #Component. When I start the spring boot app the logs show:
DEBUG [main] org.sprin.conte.annot.ClassPathScanningCandidateComponentProvider 437 scanCandidateComponents: Identified candidate component class: file [C:\Web\project\bin\main\myPackage\Config.class]
but then nothing injects the class or its beans into the app...
It looks related to this
CODE
package app;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.gemfire.config.annotation.EnableLogging;
import org.springframework.data.gemfire.repository.config.EnableGemfireRepositories;
#SpringBootApplication
#ComponentScan({"myPackage"})
#EntityScan({"myPackage"})
#EnableGemfireRepositories("region")
#EnableLogging(logLevel="info", logFile="geodeApi.log")
public class Web {
private static final Logger log = LogManager.getLogger(Web.class);
public static void main(String[] args) {
log.info("In Main");
SpringApplication app = new SpringApplication(Web.class);
app.setWebApplicationType(WebApplicationType.REACTIVE);
SpringApplication.run(Web.class, args);
log.info("Out Main");
}
}
In myPackage.Client
package myPackage;
import java.util.UUID;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.apache.logging.log4j.Logger;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.gemfire.cache.config.EnableGemfireCaching;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.EnableClusterDefinedRegions;
import org.springframework.data.gemfire.config.annotation.EnablePdx;
import org.springframework.data.gemfire.config.annotation.EnablePool;
import org.springframework.data.gemfire.config.annotation.EnablePool.Locator;
import org.springframework.data.gemfire.config.annotation.EnableStatistics;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
#ClientCacheApplication(name = "Web", logLevel = "debug")
#EnablePool(name = "webPool", subscriptionEnabled = true)
#EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.CACHING_PROXY)
#EnablePdx
#EnableStatistics
#EnableGemFireHttpSession(poolName = "webPool")
#EnableGemfireCaching
// #EnableWebFlux
public class Client {
private static final Logger log = LogManager.getLogger(Client.class);
#Resource
private Region<String, String> myAdmin;
#PreDestroy
public void onDestroy() throws Exception {
log.info("onDestroy");
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
myAdmin.put(guid, "Web Shutdown");
log.traceExit();
}
#Bean
ApplicationRunner StartedUp(){
log.traceEntry("StartedUp");
return args -> {
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
myAdmin.put(guid, "Web Started");
log.traceExit();
};
}
// Required to resolve property placeholders in Spring #Value annotations.
#Bean
static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
log.traceEntry("propertyPlaceholderConfigurer");
return new PropertySourcesPlaceholderConfigurer();
}
}
In myPackage.Config
package myPackage;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
#Configuration
public class Config {
private static final Logger log = LogManager.getLogger(Config.class);
#Bean("myRegion")
public Region<String, Object> myRegion(GemFireCache cache) {
log.traceEntry();
Region<String, Object> r = cache.getRegion("myRegion");
r.setUserAttribute(ClientRegionShortcut.CACHING_PROXY);
return r;
}
}
In Config class while defining the bean you are using Region<String, Object> as return type. Where as in the your Client class you define Region<String, String>. Here it is clearly a type mismatch and hence bean will not load.

#EnableScheduling not being recognized and creating Executor service and running scheduled jobs

Trying to modify an application to have a #Component that has a scheduled task to fire every n seconds. It seems like the executor service is never getting started to recognized there are #Components that have a #Scheduled annotation. Any ideas?
Ensured the packages are correct and should be in the componentscan base package.
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* This is the Spring Boot class for the Data Consistency Model (DCM)
*/
#EnableScheduling
#SpringBootApplication
#EnableConfigurationProperties({KafkaConfig.class, SparkConfig.class, JedisConfig.class, PrometheusConfig.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Component Class:
package com.test;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.PushGateway;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
#Component
#EnableScheduling
#EnableAsync
public class PrometheusGatewayMetricsPusher {
private static final Logger LOGGER = LogManager.getLogger(PrometheusGatewayMetricsPusher.class);
#Value("${spring.application.name}")
private String appName;
#Autowired
PushGateway pushGateway;
#Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void push() {
try {
pushGateway.push(CollectorRegistry.defaultRegistry, appName);
} catch (IOException e) {
LOGGER.log(Level.ERROR, "Error pushing to gateway. " + e.getMessage());
}
}
}
Config Class:
package com.test;
import io.prometheus.client.exporter.PushGateway;
import io.prometheus.client.hotspot.DefaultExports;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
#Getter
#Setter
#Configuration
public class MetricsConfig {
#Value("prometheus.config.gateway")
private String pushGatewayURL;
#PostConstruct
public void defaultExports() {
DefaultExports.initialize();
}
#Bean
public PushGateway pushGateway() {
return new PushGateway("localhost:9091");
}
}
I would expect the executor service to be started and initialized in the Application Context with a Thread Pool of 1. Then it would execute the #Scheduled method every second after an initial delay of 1 second. If I breakpoint in the #Component class it isn't being initialized at all.

How and where to add new bean in Sping application generated by Jhipster

I generated my Spring application using Jhipster. Now I want to add controller for FilesUpload, and StorageService for it. But when I run my application it gets me this message
Description:Parameter 0 of constructor in com.kongresspring.myapp.web.rest.FileUploadResource required a bean of type 'com.kongresspring.myapp.service.StorageService' that could not be found.
Action:Consider defining a bean of type 'com.kongresspring.myapp.service.StorageService' in your configuration.
I can't find beans.xml to add new bean. I'm new in spring, so maybe there's some other way to configure bean, I'm not familiar whit. Here's my code for uploading file controller:
package com.kongresspring.myapp.web.rest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.kongresspring.myapp.service.StorageService;
#RestController
#RequestMapping("/api")
public class FileUploadResource {
private final Logger log = LoggerFactory.getLogger(FileUploadResource.class);
private final StorageService storageService;
#Autowired
public FileUploadResource(StorageService storageService) {
this.storageService = storageService;
}
/**
* POST uploadFile
*/
#PostMapping("/upload-file")
public String uploadFile(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "success";
}
/**
* GET preview
*/
#GetMapping("/preview")
public String preview() {
return "preview";
}
}
And here's my StorageService code:
package com.kongresspring.myapp.service;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
}
You can create an implementation for StorageService, and annotate it as #Service/#Component, spring will automatically discover the bean:
#Service
public class StorageServiceImpl implements StorageService {
void init(){// You code goes here/}
void store(MultipartFile file){///}
Stream<Path> loadAll(){///}
Path load(String filename){//}
Resource loadAsResource(String filename){///}
}

Field ** in com.** required a bean of type 'com.**' that could not be found

I'm following this tutorial and I'm having some trouble starting my application.
When I run mvn spring-boot:run in the backend folder I get the following error:
Field movieRepository in com.movieseat.services.impl.MovieServiceImpl required a bean of type 'com.movieseat.repositories.MovieRepository' that could not be found.
MovieServiceIml.java
package com.movieseat.services.impl;
// Java imports
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// Spring imports
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Project imports
import com.movieseat.models.Movie;
import com.movieseat.services.MovieService;
import com.movieseat.repositories.MovieRepository;
#Service
public class MovieServiceImpl implements MovieService {
#Autowired private MovieRepository movieRepository;
#Override public List<Movie> getAllmovies() {
List<Movie> movies = new ArrayList<Movie>();
Iterator<Movie> iterator = movieRepository.findAll().iterator();
while (iterator.hasNext()) {
movies.add(iterator.next());
}
return movies;
}
}
MovieRepository.java
package com.movieseat.repositories;
// Java imports
import java.io.Serializable;
// Spring imports
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
// Project imports
import com.movieseat.models.Movie;
#Repository
public interface MovieRepository extends CrudRepository<Movie, Serializable> {}
The following structure is used:
com
movieseat
Application.java
controllers
MovieController.java
models
MovieModel.java
repositories
MovieRepository.java
services
impl
MovieServiceImpl.java
MovieService.java
And this is my Application.java:
package com.movieseat;
// Spring importss
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan({"com.movieseat.*"})
#EnableJpaRepositories("com.movieseat.repositories.*")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My thought is that using #EnableJpaRepositories("com.movieseat.repositories.*") would make all repositories accessible. But I'm doing something wrong.
Try it without * (wildcard),
#EnableJpaRepositories("com.movieseat.repositories")
Make sure you have the #Entity annotation on your Movie.

Resources