No qualifying bean of type available in SpringBoot Application - spring

When running my SpringBoot application, I am getting this error:
An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'bookController': Unsatisfied dependency expressed through field 'bookRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.experimental001.Repositories.BookRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)} -> [Help 1]
I have read through many posts regarding this error but none of them seem to fix my problem.
I have tried adding the #Controller annotation but it doesn't seem to fix the bean problem.
Controller:
#RestController
#RequestMapping("/api/books")
public class BookController {
#Autowired
private BookRepository bookRepository;
#GetMapping
public Iterable findAll() {
return bookRepository.findAll();
}
#GetMapping("/title/{bookTitle}")
public List findByTitle(#PathVariable String bookTitle) {
return bookRepository.findByTitle(bookTitle);
}
#GetMapping("/{id}")
public Book findOne(#PathVariable Long id) {
return bookRepository.findById(id)
.orElseThrow(() -> new BookNotFoundException("Book not found", null));
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public Book create(#RequestBody Book book) {
return bookRepository.save(book);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Long id) {
bookRepository.findById(id).orElseThrow(() -> new BookNotFoundException("Book not found", null));
bookRepository.deleteById(id);
}
#PutMapping("/{id}")
public Book updateBook(#RequestBody Book book, #PathVariable Long id) {
if (book.getId() != id) {
throw new BookIdMismatchException("error");
}
bookRepository.findById(id).
orElseThrow(() -> new BookNotFoundException("Book not found", null));
return bookRepository.save(book);
}
}
Simple Controller:
#Controller
public class SimpleController {
#Value("${spring.application.name}")
String appName;
#GetMapping("/")
public String homePage(Model model) {
model.addAttribute("appName", appName);
return "home";
}
}
Repository:
#EnableJpaRepositories
#Repository
public interface BookRepository extends CrudRepository<Book, Long> {
public List<Book> findByTitle(String title);
}
Pom:
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</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-thymeleaf</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application File:
#SpringBootApplication
#ComponentScan(basePackages = BookRepository)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

You might need to add the following to the main app class:
#ComponentScan(basePackages = "Package where the repository is located”)
Looks like your repository is in a different packer and spring context is not able to pick it up when starting up.
Please refer this doc: https://www.baeldung.com/spring-component-scanningfor

Related

Parse csv file by using Spring Batch and print it on console in spring Boot

My goal of the Project :
I have to read csv file by using Spring Batch and extract the specific column information like (Column Name :"msdin") "msdin" can print it on console. But my application is showing failed to start the application.
Well it is asking me to configure the data Source.Why we need to configure the data source in case of spring batch if my requirement is to read the csv file and print it on console.
I tried to identify the issues but not able to resolve. Can anybody help me how to resolve this issues?
Domain Class
public class Customer implements Serializable {
private Long id_type;
private String id_number;
private String customer_name;
private String email_address;
private LocalDate birthday;
private String citizenship;
private String address;
private Long msisdn;
private LocalDate kyc_date;
private String kyc_level;
private String goalscore;
private String mobile_network;
public Long getId_type() {
return id_type;
}
public void setId_type(Long id_type) {
this.id_type = id_type;
}
public String getId_number() {
return id_number;
}
public void setId_number(String id_number) {
this.id_number = id_number;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getEmail_address() {
return email_address;
}
public void setEmail_address(String email_address) {
this.email_address = email_address;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getMsisdn() {
return msisdn;
}
public void setMsisdn(Long msisdn) {
this.msisdn = msisdn;
}
public LocalDate getKyc_date() {
return kyc_date;
}
public void setKyc_date(LocalDate kyc_date) {
this.kyc_date = kyc_date;
}
public String getKyc_level() {
return kyc_level;
}
public void setKyc_level(String kyc_level) {
this.kyc_level = kyc_level;
}
public String getGoalscore() {
return goalscore;
}
public void setGoalscore(String goalscore) {
this.goalscore = goalscore;
}
public String getMobile_network() {
return mobile_network;
}
public void setMobile_network(String mobile_network) {
this.mobile_network = mobile_network;
}
}
BatchConfiguration class
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Value("classPath:/data/gcash.csv")
private Resource inputResource;
public ItemReader<Customer> itemReader() {
FlatFileItemReader<Customer> customerItemReader = new FlatFileItemReader<>();
customerItemReader.setLineMapper(linemapper());
customerItemReader.setLinesToSkip(1);
customerItemReader.setResource(inputResource);
return customerItemReader;
}
#Bean
public LineMapper<Customer> linemapper() {
DefaultLineMapper<Customer> linemapper = new DefaultLineMapper<>();
final DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setDelimiter(";");
tokenizer.setStrict(false);
tokenizer.setNames(new String[] { "id_type", "id_number", "customer_name", "email_address", "birthday",
"citizenship", "address", "msisdn", "kyc_date", "kyc_level", "goalscore", "mobile_network" });
linemapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<Customer>() {
{
setTargetType(Customer.class);
}
});
return linemapper;
}
}
Error Stack
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-27 11:05:46.235 ERROR 22368 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
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.4.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.gcash.milo</groupId>
<artifactId>GCash_Milo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GCash_Milo</name>
<description>Developing Milo project for GCash banking application.
</description>
<properties>
<java.version>8</java.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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-sftp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-test</artifactId>
<scope>test</scope>
</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
in your spring boot application class, add the following snippet to #SpringBootApplication annotation:
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
#SpringBootApplcation annotation uses #EnableAutoConfiguration, which expects a datasource to be configured

Parameter 0 of constructor in com.demo.service.NmpAppService required a bean named 'entityManagerFactory' that could not be found

I am trying to run a simple api flow in java spring and I am getting the following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.nmp.bts.webapps.bsc.btbsc.service.NmpAppService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.>
<Oct 25, 2019 10:37:51 AM EEST> <Notice> <Stdout> <BEA-000000> <WARN: The method class org.apache.commons.logging.impl.SLF4JLogFactory#release() was invoked.>
<Oct 25, 2019 10:37:51 AM EEST> <Notice> <Stdout> <BEA-000000> <WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.>
<Oct 25, 2019 10:37:51 AM EEST> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "48455312047066616" for task "216" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available"
weblogic.application.ModuleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:237)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:232)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
Truncated. see log file for complete stacktrace
Caused By: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
Truncated. see log file for complete stacktrace
I want to mention that I`ve tried all kind of stuffs starting from the other similar topics on stackoverflow, to change dependency and nothing worked for me.
Controller class: NmpAppController.java
#RestController
#RequestMapping("/api")
public class NmpAppController {
private final NmpAppService nmpAppService;
#Autowired
public NmpAppController(NmpAppService nmpAppService) {
this.nmpAppService = nmpAppService;
}
#GetMapping("/nmp-apps")
public List<NmpApp> getAllNmps() {
try {
return nmpAppService.getAllNmpApps();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Service class: NmpAppService.java
#Service
public class NmpAppService {
private final NmpAppRepository nmpAppRepository;
public NmpAppService(NmpAppRepository nmpAppRepository) {
this.nmpAppRepository = nmpAppRepository;
}
public NmpApp save(final NmpApp nmpApp) {
final NmpApp nmpAppToBeSaved = nmpApp;
NmpApp result = nmpAppRepository.saveAndFlush(nmpAppToBeSaved);
return result;
}
public NmpApp update(final NmpApp nmpApp) {
final NmpApp nmpAppitToBeSaved = nmpApp;
NmpApp result = nmpAppRepository.saveAndFlush(nmpAppToBeSaved);
return result;
}
public List<NmpApp> getAllNmpApps() {
return nmpAppRepository.findAll();
}
Repository class: NmpAppRepository.java
#Repository
public interface NmpAppRepository extends JpaRepository<NmpApp, Long> {
}
Domain class NmpApp.java
#Entity
#Table(name = "NMP_APP")
public class NmpApp {
#Id
#Column(name = "SEQ_NO")
private Long seqNo;
#Column(name = "HIST_DATE")
private Long histDate;
public NmpApp() {
}
public NmpApp(Long seqNo, Long histDate) {
this.seqNo = seqNo;
this.histDate = histDate;
}
public Long getSeqNo() {
return seqNo;
}
public void setSeqNo(Long seqNo) {
this.seqNo = seqNo;
}
public Long getHistDate() {
return histDate;
}
public void setHistDate(Long histDate) {
this.histDate = histDate;
}
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>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nmp.bts.webapps.bsc</groupId>
<artifactId>nm-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>bt-bsc</name>
<description>BSC</description>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-data-jdbc</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</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-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Spring boot main class: Application.java
#EnableTransactionManagement
#SpringBootApplication(exclude = {HibernateJpaAutoConfiguration.class})
public class Application extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.getSessionCookieConfig().setHttpOnly(false);
super.onStartup(servletContext);
}
}
Later Edit: I uploaded the application.properties file
#Basic Spring Boot Config for Oracle
spring.datasource.url= jdbc:oracle:thin:#//:/
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.jndi-name=jdbc/DEV_ADF_APPLDS
#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.main.allow-bean-definition-overriding=true
I want to be able to perform simple CRUD operations on a database via swagger api caller (code shows only getAll but I do have the rest of code tho).
Usually happens when Spring is missing the spring-boot-starter-data-jpa since Spring infers the EntityManager from the Spring Data JPA which has an out of the box implementation for Hibernate ORM.
Adding the following to project pom.xml usually solves this problem
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
But in your case is available so the offending code is
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Change to
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
Instead of spring-boot-starter-data-rest, try using the following
"org.springframework.boot:spring-boot-starter-data-jpa"
"org.springframework.boot:spring-boot-starter-jdbc"
Later edit: Also, don't forget to add #EnableTransactionManagement on the spring boot main class or on the database configuration class

spring boot fails to start-- define a bean of type 'TopicRepository' in configuration

I was following this JavaBrains tutorials of Spring Boot.
My project structure is as follows:
CourseApiApp.java:
#SpringBootApplication
#ComponentScan(basePackages = {
"com.bloodynacho.rishab.topics"
})
#EntityScan("com.bloodynacho.rishab.topics")
public class CourseApiApp {
public static void main(String[] args) {
SpringApplication.run(CourseApiApp.class, args);
}
}
TopicController.java:
#RestController
public class TopicController {
#Autowired
private TopicService topicService;
#RequestMapping(
value = "/topics"
)
public List<Topic> getAllTopcs() {
return topicService.getAllTopics();
}
}
TopicService.java:
#Service
public class TopicService {
#Autowired
private TopicRepository topicRepository;
public List<Topic> getAllTopics() {
List<Topic> topics = new ArrayList<>();
this.topicRepository
.findAll()
.forEach(topics::add);
return topics;
}
}
Topic.java:
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
}
TopicRepository.java:
#Repository
public interface TopicRepository extends CrudRepository<Topic, String>{
}
pom.xml:
<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.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</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>
I was using the lombok #Getter, #Getter and #AllArgsConstructor in Topic.java but I removed it after reading one of the answers here.
I read this1, this2, this3
Still, I get
***************************
APPLICATION FAILED TO START
***************************
Description:
Field topicRepository in com.bloodynacho.rishab.topics.TopicService required a bean of type 'com.bloodynacho.rishab.topics.TopicRepository' 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.bloodynacho.rishab.topics.TopicRepository' in your configuration.
Process finished with exit code 1
EDIT: I read this explaining how even without actually implementing the interface the #Autowired works. I understand the solution, but I don't understand how to solve my issue. Clearly, there is some problem with the way Spring Data is set up and configured (as mentioned in the answer)
Because if your other packages hierarchies are below your main application with the #SpringBootApplication annotation, you’re covered by implicit components scan.
Therefore, one simple solution can be done by following 2 steps:
Rename the package of main class to be com.bloodynacho.rishab.
(That is what I suggest that the complete package name of main app. is supposed to be root of other packages.)
Remove #ComponentScan and #EntityScan annotation.
(Although #ComponentScan is different from #EntityScan, it can be also removed in my experience.)

#DeleteMapping not recognized

I am new with spring boot, is very simple my question but I can´t find where is the problem.
I have a basic #GetMapping and #DeleteMapping
#RestController
public class MyController
{
private MyServiceImpl myService;
#Autowired
public MyController(MyServiceImpl myService)
{
this.myService = myService;
}
#GetMapping("/test")
public List<Scan> getTestData(#RequestParam(value = "test_id", required = true) String test_id) {
return myService.findByTestId( test_id );
}
#DeleteMapping("/test")
public int deleteData(#RequestParam(value = "test_id", required = true) String test_id){
return myService.deleteTest( test_id );
}
#DeleteMapping("/test2")
public String deleteArticle() {
return "Test";
}
}
I am testing with Postman, the Get request is working, but the delete request is not. Even when I debug the spring boot application. The GetMapping is called, whereas the delete is not "reacting" /called
Maybe is not enough information, but I even tested #DeleteMapping("/test2") is not doing anything, I mean, I get no response, and in Postman it stays "loading..."
Any suggestions?
My complete POM
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<parent>
<groupId>com.ttt.pdt</groupId>
<artifactId>pdt-base</artifactId>
<version>2.0-SNAPSHOT</version>
</parent>
<artifactId>pdt-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
The parent (pdt-base) has
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
MyServiceImpl
#Service
public class MyServiceImpl
{
private ScnDao scnDao;
#Autowired
public ScanServiceImpl(ScnDao scnDao){
this.scnDao = scnDao;
}
public int deleteTest( String test_id )
{
return scnDao.deleteTest( test_id );
}
}
public interface ScanDao
{
int deleteTest( String test_id )
}
#Repository
public class ScnPostgres implements ScnDao
{
private JdbcTemplate jdbcTemplate;
#Autowired
public ScnPostgres( JdbcTemplate jdbcTemplate )
{
this.jdbcTemplate = jdbcTemplate;
}
public int deleteTest( String test_id )
{
String SQL = "DELETE FROM scn WHERE test_id = ?";
return jdbcTemplate.update( SQL, new String[] { test_id } );
}
}
As in SPR comments described SPR-16874:
it does not support DELETE currently. It would be a trivial change to
make. There is suggested a workaround:
#DeleteMapping(value = "/greeting")
public Greeting handle(#RequestBody MultiValueMap<String, String> params) {
return new Greeting(counter.incrementAndGet(),
String.format(template, params));
}
As you can see the issue has been opened in the spring boot tracker.

Spring Data Repository Autowiring troubles

Im having trouble autowiring my CrudRespository in my Controller (I am using Spring boot).
Here are my Controller,Entity & Respository implementations
Repository:
package com.nbha.micro.ratingService;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface RaterDORepository extends CrudRepository<RaterDO, Long> {
public RaterDO findByRaterName();
}
Entity:
#Entity
public class RaterDO {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long raterId;
public RaterDO(){}
public RaterDO(String n) {
this.raterName = n;
}
public Long getRaterId() {
return raterId;
}
public void setRaterId(Long raterId) {
this.raterId = raterId;
}
public String getRaterName() {
return raterName;
}
public void setRaterName(String raterName) {
this.raterName = raterName;
}
private String raterName;
}
Controller:
#RestController
#RequestMapping("/raters")
public class RaterController {
#Autowired
private RaterDORepository raterDORepository;
#RequestMapping("/add")
public String addRater(#RequestParam("name") String name) {
RaterDO raterDO = new RaterDO(name);
raterDORepository.save(raterDO);
return "Rater:" + name +" saved.";
}
#RequestMapping("/allRaters")
public String getAllRaters() {
StringBuilder sb = new StringBuilder();
sb.append("|");
Iterable<RaterDO> raters = raterDORepository.findAll();
for(RaterDO rater : raters) {
sb.append(rater.getRaterName());
sb.append("|");
}
return sb.toString();
}
}
Starter class:
#EnableBinding(ConsumerChannels.class)
#ComponentScan(basePackages={"com.nbha.micro.ratingService"})
#EntityScan(basePackages={"com.nbha.micro.ratingService"})
#EnableJpaRepositories(basePackages={"com.nbha.micro.ratingService"})
#SpringBootApplication
#EnableEurekaClient
#RestController
#RequestMapping("/ratings")
public class RatingApp
{
public static void main( String[] args )
{
System.out.println( "Invoking Rating Service.." );
SpringApplication.run(RatingApp.class, args);
}
#StreamListener(ConsumerChannels.PRODUCER)
public void receiveRater(final Rater rater) {
if(rater != null) {
System.out.println("Rating received in the rating-service:" + rater.getName());
}
}
private List<Rating> ratingList = Arrays.asList(
new Rating("R101","101",5),
new Rating("R102","102",2),
new Rating("R103","101",4),
new Rating("R104","101",1)
);
#GetMapping("/all")
public List<Rating> findAllRatings() {
return this.ratingList;
}
#GetMapping("/rating-agency")
public String whichRatingAgency() {
return "Moody's";
}
#GetMapping("")
public List<Rating> findRatingsByBookId(#RequestParam String bookId) {
Rating r;
List<Rating> rList = new ArrayList<Rating>();
ListIterator iter = this.ratingList.listIterator();
while(iter.hasNext()) {
r = (Rating)iter.next();
if(r.getBookId().equals(bookId)) {
rList.add(r);
}
}
return rList;
}
}
interface ConsumerChannels {
String PRODUCER = "producer";
#Input
SubscribableChannel producer();
}
I placed all these classes in the same package (in a desparate bid to make it work)
I keep getting the following error on application startup (fails to startup).The interesting thing is that a similar setup works in another instance without using #ComponentScan #EntityScan #EnableJpaRepository annotations :)
Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'raterController': Unsatisfied dependency expressed through field 'raterDORepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'raterDORepository': Invocation of init method failed; nested exception is java.util.NoSuchElementException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
....
Caused by: org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'raterDORepository': Invocation of init method failed; nested exception is java.util.NoSuchElementException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans- 4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
....
Caused by: java.util.NoSuchElementException: null
at java.util.ArrayList$Itr.next(ArrayList.java:860) ~[na:1.8.0_151]
at org.springframework.data.jpa.repository.query.ParameterMetadataProvider.next(ParameterMetadataProvider.java:122) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:302) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:208) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
....
Any clues will be appreciated. Here are my dependencies from pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies`enter code here`</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
public RaterDO findByRaterName(); needs a parameter, something like public RaterDO findByRaterName(String name).
Construction of the repository fails because the missing parameter prevents Spring Data to construct a proper method.

Resources