Getting #Autowired error - java

I'm getting an error whenever I'm using #Autowired annotation. The root error i get is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [jp.co.vmt.qt.C0002.C0002Dao] 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)}
My interface is
/**
*
*/
package jp.co.vmt.qt.C0002;
import java.util.List;
import jp.co.vmt.qt.model.TmtProject;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
/**
* #author WINDOWS
*/
public interface C0002Dao extends JpaRepository<TmtProject, Long> {
#Query("SELECT PROJECT_ID, PROJECT_NAME FROM TmtProject")
public List<TmtProject> getAllProjects();
}
And my implementing class is
/**
*
*/
package jp.co.vmt.qt.C0002;
import java.util.List;
import jp.co.vmt.qt.model.TmtProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
/**
* #author WINDOWS
*/
#Repository
public class C0002Service implements C0002Dao {
#Autowired
private C0002Dao c0002Dao;
/*
* (non-Javadoc)
* #see jp.co.vmt.qt.C0002.C0002Dao#getAllProjects()
*/
#Override
public List<TmtProject> getAllProjects() {
return this.c0002Dao.getAllProjects();
}
... other methods from extended interface
}
And here is where I used c0002Service
/**
*
*/
package jp.co.vmt.qt.C0002;
import java.util.List;
import jp.co.vmt.qt.model.TmtProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* #author WINDOWS
*/
#Component
public class C0002Logic {
#Autowired
private C0002Dao c0002Service;
public String getProjectList() throws Exception {
List<TmtProject> projectList = this.c0002Service.getAllProjects();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(projectList);
return jsonString;
}
}
I have my C0002Logic autowired in my controller which is not shown here.
To my understanding, I created an interface (C0002Dao) and an implementing class (C0002Service) of that interface, which I marked with #Repository and I am autowiring the service to my Logic class (C0002Logic). However, I'm getting the error shown above. Any ideas on where I went wrong and how to solve them? Thanks

The problem is I believe
In C0002Service,
#Autowired
private C0002Dao c0002Dao;
U r trying to inject to C0002Dao at the time qualifying bean (instance of C0002Service) is about to be registered.

Related

Quarkus reactive : test Mutli<Response>

Introduction
I'm working on a project that uses Quarkus Reactive.
And currently I made a method that returns a Multi, but I can't test this one.
I would like to ensure that all responses in the Multi have a code of 2XX.
And check the content of each answer.
The codes:
package com.xx.xx.xx.rest;
import com.xx.xx.xx.domain.customerprofile.CustomerProfileService;
import com.xx.xx.xx.infrastructure.binding.CustomerProfileMapper;
import com.xx.xx.xx.rest.annotation.ValidationGroups;
import com.xx.xx.xx.rest.dto.customerprofile.CustomerProfileDTO;
import com.xx.xx.xx.rest.exception.ErrorCode;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.groups.ConvertGroup;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.util.Collection;
/**
* BulkImportResource is a rest resource class for bulk import of customer profiles.
*
* #version 1.0.0
*/
#Path("/bulkimport")
public class BulkImportResource {
private final CustomerProfileService customerProfileService;
/**
* Instantiates a new Customer profile resource.
*
* #param customerProfileService the customer profile service
*/
#Inject
public BulkImportResource(CustomerProfileService customerProfileService) {
this.customerProfileService = customerProfileService;
}
/**
* Bulk import of customer profiles.
*
* #param customerProfileDTOs the list of customer profiles to import
* #return the list of customer profiles
*/
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Multi<Response> postFormReturnAddedObject(#NotNull(message = ErrorCode.Constants.ERROR_EMPTY_BODY)
Collection<CustomerProfileDTO> customerProfileDTOs) {
return Multi.createFrom().items(customerProfileDTOs.parallelStream())
.onItem().transformToUniAndMerge(this::createCustomerProfileAndBuildResponse);
}
private Uni<Response> createCustomerProfileAndBuildResponse(
#Valid #ConvertGroup(to = ValidationGroups.Post.class) CustomerProfileDTO customerProfileDTO) {
return customerProfileService.createCustomerProfile(
CustomerProfileMapper.INSTANCE.dtoToDomain(customerProfileDTO))
.map(CustomerProfileMapper.INSTANCE::domainToDTO)
.map(dto -> Response
.created(UriBuilder.fromPath("customerProfiles/{id}")
.build(dto.getId()))
.entity(dto))
.map(Response.ResponseBuilder::build);
}
}
The test:
#QuarkusTest
#Tag("IntegrationTest")
#TestHTTPEndpoint(BulkImportResource.class)
#QuarkusTestResource(value = CouchbaseTestContainer.class)
public class BulkImportResourceIntegrationTest {
private static final String JSON_FILE_NAME = "/profiles.json";
private static File jsonFile;
private List<CustomerProfileDTO> customerProfileDTOList;
#BeforeAll
public static void setUpAll() {
jsonFile = new File(Objects.requireNonNull(MultipartBodyUnitTest.class.getResource(JSON_FILE_NAME)).getFile());
}
#BeforeEach
public void setUp() throws IOException {
var objectWriter = new ObjectMapper();
customerProfileDTOList = List.of(objectWriter.readValue(jsonFile, CustomerProfileDTO[].class));
}
#Test
void createCustomerProfile() throws IOException {
var responses = given()
.contentType(ContentType.JSON)
.body(customerProfileDTOList)
.when().post()
.then()
.extract().as(Response[].class);
}
}
This test doesn't work, the returned error :
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `javax.ws.rs.core.Response` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (String)"[{"status":201,"entity":{"id":"5","cas":1642517845455405056,"created":"2022-01-18T15:57:25Z","lastName":"DUPOND","firstName":"Marianne","gender":"FEMALE","title":"MRS","addresses":[{"street1":"rue du Testeur","zipCode":"34000","city":"MONTPELLIER","country":"France","typeKey":"PERSONAL"}],"phones":[{"number":"0610529856","typeKey":"PERSONAL"}],"emails":[{"email":"marianne.dupond#test.com","typeKey":"PERSONAL"}],"birthday":"1987-11-13","languages":["FR","EN"],"socialNetworks":[{"socialNetworkId":"[truncated 2143 chars]; line: 1, column: 2] (through reference chain: java.lang.Object[][0])
Outro
Someone have a solution for this problem ?

Java, Springboot, MongoDB extend SimpleMongoRepository (2020)

I've found many problems with this here in Stackoverflow.
But they are all in few years back. Hoping to find an updated solution.
I'm Extending SimpleMongoRepository in my own class to add some custom methods
Here is my code. MongoHelper.java
package com.customlibrary.mongodblibrary.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
#Component
public class MongoHelper<T, ID extends Serializable> extends SimpleMongoRepository<T, ID> implements
CustomerRepository<T , ID> {
/**
* Creates a new {#link SimpleMongoRepository} for the given {#link MongoEntityInformation} and
{#link MongoTemplate}.
*
* #param metadata must not be {#literal null}.
* #param mongoOperations must not be {#literal null}.
*/
public MongoHelper(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
super(metadata, mongoOperations);
}
public void customMeth(){
System.out.println("test");
}
}
Here is my code. CustomerRepository.java
#Repository
public interface CustomerRepository<Customer, String> extends MongoRepository<Customer, String> {
}
And I already put this in my Main
#EnableMongoRepositories(repositoryBaseClass = MongoHelper.class)
But there's a error showing up
Parameter 0 of constructor in com.customlibrary.mongodblibrary.service.MongoHelper required a bean of type 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' that could not be found.
Hoping Someone can give me a solution
Use #NoRepositoryBean instead of #Component for MongoHelper since MongoHelper is supposed to be a base class to be extended and not a bean managed by Spring

Spring boot test unable to autowire service class

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!

Aspect Oriented Programming in Spring error when I implements interface

I'm studying Aspect Oriented Programming in Spring with #AspectJ
I write an example but when I run it I've an error
Here are the class that I write
package concert;
/**
*
* #author phate
*/
public interface Performance {
public void perform();
}
Class PerformanceImpl implements the Performance interface and implements perform method
package concert;
import org.springframework.stereotype.Service;
/**
*
* #author Dennis A. Boanini
*/
#Service
public class PerformanceImpl implements Performance{
#Override
public void perform() {
System.out.println("perform");
}
}
Class Audience is annotated with #Aspect and declare some Advice
package concert;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
*
* #author Dennis A. Boanini
*/
#Component
#Aspect
public class Audience {
#Before("execution(* concert.Performance.perform(..))")
public void silenceCellPhones(){
System.out.println("Silencing cell phones");
}
#Before("execution(* concert.Performance.perform(..))")
public void takeSeats(){
System.out.println("Taking seats");
}
#AfterReturning("execution(* concert.Performance.perform(..))")
public void applause(){
System.out.println("CLAP CLAP CLAP");
}
#AfterThrowing("execution(* concert.Performance.perform(..))")
public void demandRefund(){
System.out.println("Demanding a refund");
}
}
Class ConcertConfig is the bean that autoproxy
package concert;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
*
* #author Dennis A. Boanini
*/
#Configuration
#EnableAspectJAutoProxy
#ComponentScan
public class ConcertConfig{
#Bean
public Audience audience() {
return new Audience();
}
}
And this is the main class
public class Turing {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConcertConfig.class);
ctx.refresh();
Performance userService = ctx.getBean(PerformanceImpl.class);
userService.perform();
}
}
If I run I receive this error
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [concert.PerformanceImpl] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:374)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1088)
at com.phate.spring.aop.example.Turing.main(Turing.java:32)
But if I eliminate the interface everything work correctly, why?

Spring Autowired service and controller not working

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", ...}

Categories