OK, before the downvotes come here is how this question is different from:
Repository Injection not been recognized as bean: Annotating the main class to make it scan the base package does not work for me.
'Field required a bean of type that could not be found.' error spring restful API using mongodb: well, I'm not using MongoDB, but even if I was, the answers to that question do not solve my problem. My packages are set up correctly, I tried the #Service annotation, made sure IntelliJ imported the right Service, tried annotating the controller with #Component, made sure there's no 2 beans with the same name, renamed the Bean Spring refused to see, tried clearing the cache of IntelliJ, restarted my machine, nothing.
D:.
│ .classpath
│ .project
│ DiscordConfApplication.java
│
├───bin
├───controller
│ Controller.java
│ DiscordUserController.java
│
├───entity
│ DiscordEntity.java
│ DiscordUser.java
│ Guild.java
│ Member.java
│ Permissions.java
│ Role.java
│ Settings.java
│
└───service
DiscordUserRepo1.java
DiscordUserService.java
This is the structure of my project. com.example.discordconf is defined as package and it contains bin, controller, entity and service.
When I try to run my Spring app I get this error:
APPLICATION FAILED TO START
***************************
Description:
Field discordUserRepo1 in com.example.discordconf.service.DiscordUserService required a bean of type 'com.example.discordconf.service.DiscordUserRepo1' 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.example.discordconf.service.DiscordUserRepo1' in your configuration.
Here is DiscordUserRepo1.java itself:
import com.example.discordconf.entity.DiscordUser;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DiscordUserRepo1 extends JpaRepository<DiscordUser, Integer> {
//Optional<DiscordUser> findById(Integer integer);
}
DiscordUserService.java
import com.example.discordconf.entity.DiscordUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class DiscordUserService {
#Autowired
DiscordUserRepo1 discordUserRepo1;
public void addNewDiscordUser(DiscordUser discordUser) {
discordUserRepo1.save(discordUser);
}
public List<DiscordUser> getAllDiscordUsers() {
return discordUserRepo1.findAll();
}
public Optional<DiscordUser> getById(int id) {
return discordUserRepo1.findById(id);
}
}
Controller.java
import com.example.discordconf.entity.DiscordUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.discordconf.service.DiscordUserService;
#RestController
public class Controller {
#Autowired
DiscordUserService discordUserService;
#PostMapping("/adduser")
public void addNewDiscordUSer(#RequestBody DiscordUser discordUser) {
discordUserService.addNewDiscordUser(discordUser);
}
}
DiscordUserController.java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class DiscordUserController {
#GetMapping("/")
public String home() {
return "<h1>Welcome to Discord Conf!</h1>";
}
}
DiscordConfApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages="com.example.discordconf")
//#EnableJpaRepositories(basePackages = {"com.example.discordconf.Service"})
public class DiscordConfApplication {
public static void main(String[] args) {
SpringApplication.run(DiscordConfApplication.class, args);
}
}
What am I supposed to do? I've been trying to solve this for days and it makes me wanna tear my hair out.
I think you need to add #Repository to the DiscordUserRepo1 class
Related
I am attempting to create a Spring Boot test class which should create the Spring context and autowire the service class for me to test.
This is the error I am getting:
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.gobsmack.gobs.base.service.FileImportService' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
The file structue:
The Test class:
package com.example.gobs.base.service;
import com.example.gobs.base.entity.FileImportEntity;
import com.example.gobs.base.enums.FileImportType;
import lombok.val;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
#DataJpaTest
#RunWith(SpringRunner.class)
public class FileImportServiceTest {
#Autowired
private FileImportService fileImportService;
private FileImportEntity entity;
The Main application class:
package com.example.gobs.base;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Used only for testing.
*/
#SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
FileImportService interface:
package com.example.gobs.base.service;
import com.example.gobs.base.entity.FileImportEntity;
import com.example.gobs.base.enums.FileImportType;
import java.util.List;
public interface FileImportService {
/**
* List all {#link FileImportEntity}s.
Which is implemented by:
package com.example.gobs.base.service.impl;
import com.example.gobs.base.entity.FileImportEntity;
import com.example.gobs.base.enums.FileImportType;
import com.example.gobs.base.repository.FileImportRepository;
import com.example.gobs.base.service.FileImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class FileImportServiceImpl implements FileImportService {
#Autowired
private FileImportRepository repository;
#Override
public List<FileImportEntity> listAllFileImportsByType(FileImportType type) {
return repository.findAllByType(type.name());
}
Why can it not find the implementation?
#DataJpaTest annotation doesn't make services loaded to the application context. From Spring documentation: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test
You can use the #DataJpaTest annotation to test JPA applications. By default, it scans for #Entity classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. Regular #Component beans are not loaded into the ApplicationContext.
You could use #SpringBootTest annotation instead of DataJpaTest. Hope that helps!
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 3 years ago.
I am developing a spring boot application to send sms notification. This is my class for the purpose.
package org.otp.services;
import org.otp.Configurations;
import com.mashape.unirest.http.HttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
#Component
public class SmsService
{
private static final Logger LOG = LoggerFactory.getLogger(SmsService.class);
public String send(String mobile, String msg)
{
//Code
}
}
And this is the class which uses the above class for sending notification.
package org.otp.controllers;
import org.otp.Constants;
import org.otp.services.EmailService;
import org.otp.services.SmsService;
import org.otp.dto.MessageRequest;
import org.otp.dto.MessageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
#Component
public class MessageController {
private static final Logger LOG = LoggerFactory.getLogger(MessageController.class);
#Autowired
SmsService smsService;
public void sendMessageToAlert(#RequestBody MessageRequest messageRequest)
{
String smsStatus = "FAIL";
MessageResponse messageResponse = new MessageResponse();
//1. Nullpointer
smsStatus = smsService.send(messageRequest.getMobileNo(),messageRequest.getMessage());
}
}
Main Class
package org.otp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
#SpringBootApplication
#EnableAsync
public class OtpServiceApplication implements ApplicationRunner
{
public static void main(String[] args) {
SpringApplication.run(OtpServiceApplication.class, args);
}
}
Problem is, I get a nullpointer exception in the (1) stating that my SmsService object is null. And my main class is in package org.otp so the two classes here falls under sub package so no need of component scan.
Therefore I am confused what to do to solve this. I have tried many answers here like adding a #Component annotation and #ComponentScan in main class but nothing works. Could someone please point out my mistake here.
Thanks in advance.
If your #Autowired annotation is not working and throws NPE ,it means that spring fails to create an instance of the component class in the application context . Try to:
Verify that the classes are in class path for scanning and also check to ensure that all auto-wired classes have the annotation #Component to enable them to be picked up during class path scanning.
Check the spring boot start up logs to verify if there are any errors
during bean creation.
Check to ensure all related classes used in the service layer are auto-wired properly and that the injected classes are annotated with #Component .
For further help please share the main application class along with your project structure.
Since you are using springboot , it is preferable to use the sprinboot stereotype annotations instead of the #Component annotation, if you are building a standard springboot web application.
#Service : for the service layer.
#Controller : for the controller layer . Also,DispatcherServlet will look for #RequestMapping on classes which are annotated using #Controller but not with #Component.
In Springboot application's main class add following annotation
#SpringBootApplication
#ComponentScan(
basePackages = {"org.otp.*"}
)
public class YourSpringMainClass{
public static void main(String[] args) {
SpringApplication.run(YourSpringMainClass.class, args);
}
}
While using annotations we should configured with #ComponentScan annotation to tell Spring the packages to scan for annotated components. This should be used in mail class(Which class wants to load first) in your case you are working with spring boot so you should use this annotation in Springboot application's main class. Like below
#SpringBootApplication
#ComponentScan(
basePackages = {"org.otp.*"}
)
public class YourSpringMainClass{
public static void main(String[] args) {
SpringApplication.run(YourSpringMainClass.class, args);
}
}
Im new in Spring Boot. I have to connect my app to MySQL servver. At thetime of creating back side of app, I got a problem with beans in Spring. When I try to run this in my server I get the error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bagyt.reposotories.UniversityRepository' available: expected at least 1 bean which qualifies as an autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is my controller class
package com.bagyt.controller;
import com.bagyt.exception.ResourceNotFoundException;
import com.bagyt.model.University;
import com.bagyt.repositories.UniversityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
#RestController
#RequestMapping("/universityApi")
public class UniversityController {
#Autowired
UniversityRepository universityRepository;
#GetMapping("/university")
public List<University> getAllNotes() {
return universityRepository.findAll();
}
#PostMapping("/university")
public University createNote(#Valid #RequestBody University note) {
return universityRepository.save(note);
}
#GetMapping("/university/{id}")
public University getNoteById(#PathVariable(value = "id") Long universityId) {
return universityRepository.findById(universityId)
.orElseThrow(() -> new ResourceNotFoundException("University", "id", universityId));
}
#PutMapping("/university/{id}")
public University updateNote(#PathVariable(value = "id") Long universityId,
#Valid #RequestBody University universityDetails) {
University university = universityRepository.findById(universityId)
.orElseThrow(() -> new ResourceNotFoundException("University", "id", universityId));
university.setName(universityDetails.getName());
university.setEmail(universityDetails.getEmail());
university.setDescription(universityDetails.getDescription());
university.setPhotoLink(university.getPhotoLink());
University updatedNote = universityRepository.save(university);
return updatedNote;
}
#DeleteMapping("/university/{id}")
public ResponseEntity<?> deleteNote(#PathVariable(value = "id") Long universityId) {
University note = universityRepository.findById(universityId)
.orElseThrow(() -> new ResourceNotFoundException("University", "id", universityId));
universityRepository.delete(note);
return ResponseEntity.ok().build();
}
}`
My repository
package com.bagyt.repositories;
import com.bagyt.model.University;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UniversityRepository extends JpaRepository<University, Long> {
}
I have tested and made sure the error is in my #Autowired line in the controller.
Thanks for any help!
As docs says about #SpringBootApplication
#ComponentScan: enable #Component scan on the package where the application is located
That means Spring will look for beans in your com.bagyt.controller, that is the same package where a class annotated with #SpringBootApplication has been defined and its subpackages.
You should move BagytApplication in com.bagyt package if you want to scan for components in other packages such as com.bagyt.repository.
Check your controller package is either same package or sub package of class with #springBootApplication. If any dependency(#controller,#Service,#Repository) is in different package structure use #componentscan(give package name ).I think it should work.
On springboot main class, you can add
#EnableJpaRepositories(basePackages = "com.bagyt.repositories")
I read a lot about this kind of problem here, but it seems my code is good but the autowire is not working :
Error creating bean with name 'optionController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private service.InteractionBanque controllers.OptionController.interactionBanque; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.InteractionBanque] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Here is the code of my Controller :
package controllers;
package controllers;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import model.Banque;
import model.Client;
import service.InteractionBanque;
import serviceimpl.InteractionBanqueImpl;
#Controller
public class OptionController {
#Autowired
private InteractionBanque interactionBanque;
#RequestMapping(value="/virement",method=RequestMethod.GET)
public String index(Model model, #ModelAttribute Client client) {
model.addAttribute("virement", new Virement());
return "virement";
}
#RequestMapping(value="/virement",method=RequestMethod.POST)
public String index(#ModelAttribute Virement virement, Model model) {
return "options";
}
}
And the Code of my Service :
package serviceimpl;
import java.util.HashMap;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import dao.BanqueDAO;
import daoimpl.BanqueDaoImpl;
import model.Banque;
import model.Client;
import service.InteractionBanque;
import utils.SendRequest;
#Service
public class InteractionBanqueImpl implements InteractionBanque {
public static final int END_ID_BANQUE = 5;
public static final String LOGIN_URL = "/account";
public boolean connecter(Client client) {
some code
}
}
And The code of the interface :
package service;
public interface InteractionBanque {
boolean connecter(Client client);
}
And my Application class define the #SpringBootApplication which should be use to wire everything :
package controllers;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
SO I don't get it, for me this should do the work but the autowired is not working.
Help would be appreciated :)
#SpringBootApplication scans only package (recursively) within a class that uses it. InteractionBanqueImpl is in another package.
Create a package 'app' with Application class, and then move to it controllers and and other packages. Should be fine.
As #Mati said, you have a problem with packages.
Create a root package for your application and move everything under it, so you have it something like this:
+ myapp
Application.java
+ controller
+ service
+ serviceimpl
The answers you have about putting your Application class in a parent package of the rest of your code will work, but an alternative, if you don't want to change your package structure, would be to use the #ComponentScan annotation, specifying the packages that contain components you want to autowire, for example:
#ComponentScan(basePackages = {"serviceimpl", ...}
I have 2 projects:
The imported project from spring starting guides
Another project which has the same directory structure and the same code
The first one works but the second one gives me a 404 error.
I have print screened the directory structure for both of them.
Here is the PostController.java code:
package Post;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class PostController {
#RequestMapping("/post")
public String index(Model model)
{
System.out.println("Template's fault");
return "index_posts";
}
}
Here is the GreetingController.java code:
package hello;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class GreetingController
{
#RequestMapping("/greeting")
public static String index(#RequestParam(value="n1",required=false,defaultValue="1")String n1,#RequestParam(value="n2",required=false,defaultValue="2")String n2,Model mod)
{
MathApp mathapp = new MathApp(n1,n2);
int result = mathapp.addNumbers();
mod.addAttribute("result", result);
return "greeting";
}
}
Here is the code that both Application.java files share ( exception being the package):
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The blog when run gives a 404 error while the gs-serving-web-content-inital when run works like a charm. The MathApp in GreetingController is simply a model and does not affect the app. The pom.xml is quite the same exception being that mysql dependencies are loaded into the blog app.
Thank you
--EDIT--
I'm trying to access http://localhost:8080/post
The app does deploy succesfully