I use psring boot 2, postgres and Jpa with hibernate.
I would like to test one of my class
#Component
public class ExportsFacade {
private SamplesService sampleService;
private SamplesRepository sampleRepository;
#Autowired
public ExportsFacade(SamplesService sampleService, SamplesRepository sampleRepository) {
this.sampleService = sampleService;
this.sampleRepository=sampleRepository;
}
...
}
I created this test
#RunWith(SpringRunner.class)
#DataJpaTest
#AutoConfigureTestDatabase(replace=Replace.NONE)
public class ExportsFacadeTest {
#Autowired
private ExportsFacade exportsFacade;
#Test
public void export() throws IOException {
exportsFacade.generateExport();
}
}
I get this error
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'com.lcm.facade.ExportsFacadeTest':
Unsatisfied dependency expressed through field 'exportsFacade'; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'com.lcm.facade.ExportsFacade' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Related
I want to create a utility class just for my tests that have some methods that all tests will use to reduce code duplication.
Where do I create this class and how do I import it in my tests?
Errors
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'FooTest': Unsatisfied dependency
expressed through field 'myTestUtils'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.utils.MyTestUtils' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Files
// src/test/com/example/utils/MyTestUtils.java
public class MyTestUtils {
public String foo = "bar";
}
// src/test/com/example/services/FooTest.java
import com.example.utils.TestUtils;
#SpringBootTest
public class FooTest {
// If I remove this decorator I get that this.testUtils is null
#Autowired
MyTestUtils myTestUtils
#Test
public void testFoo() throws Exception {}
Asserthat(myTestUtils.foo).equals("bar")
}
Update
I solved the problem above with annotating the myTestUtils class with #Service
This works.
// src/test/com/example/utils/MyTestUtils.java
#Service
public class MyTestUtils {
public String foo = "bar";
}
I have spring application and have defined the Clock bean in my SpringMvcConfig.java as follows
#Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
I am using it in my service
#Service
#RequiredArgsConstructor
#Slf4j
public class DeliveryEstimationService {
#NonNull
private final SalesChannelService salesChannelService;
#NonNull
private final MessageSource messageSource;
#NonNull
private final Clock clock;
public List<LocalDateTime> applyCutoffHoursToLocalDate(List<Integer> cutoffWindowHourList, int plusDays) {
return cutoffWindowHourList.stream().map(cutoffWindowHour -> LocalDateTime.of(
LocalDate.now(clock), LocalTime.of(cutoffWindowHour, 0)).plusDays(plusDays))
.collect(Collectors.toList());
}}
And I see this error
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 83 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'deliveryEstimationService' defined in file [/home/runner/work/checkout-service/checkout-service/target/classes/com/checkout/delivery/DeliveryEstimationService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.time.Clock' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798)
Can someone tell me why spring app cannot create the bean?
I had to use clock because I need to set fixed time for testing purpose
void getFixedClock(LocalDate date) {
fixedClock = Clock.fixed(date.atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());
doReturn(fixedClock.instant()).when(clock).instant();
doReturn(fixedClock.getZone()).when(clock).getZone();
}
I am in the process of learning spring boot, however, I encountered a problem and I can not find a solution. When I try to run the test, I get the following exception.
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImplementation' defined in file []: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileServiceImplementation' defined in file []: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileServiceImplementation' defined in file []: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I tried to put an annotation in different places, but it did not solve my problem. I completely don't know how should I create ModelMapper bean. Maybe you will know how to deal with it. Here is my code:
BookServiceImplementation.class
#Service
public class BookServiceImplementation implements BookService {
private BookRepository bookRepository;
private UploadFileService uploadFileService;
private ModelMapper modelMapper;
#Autowired
public BookServiceImplementation(BookRepository bookRepository, UploadFileService uploadFileService,
ModelMapper modelMapper){
this.bookRepository = bookRepository;
this.uploadFileService = uploadFileService;
this.modelMapper = modelMapper;
}
#Override
public void addBook(AddBookResource addBookResource) {
Book book = new Book();
Long coverImageId = addBookResource.getCoverImageId();
Long contentId = addBookResource.getContentId();
UploadFile coverImage = null;
UploadFile bookContent = null;
if (coverImage != null){
coverImage = uploadFileService.findById(coverImageId)
.map(fileResource -> modelMapper.map(fileResource, UploadFile.class))
.orElse(null);
}
if (contentId != null){
bookContent = uploadFileService.findById(contentId)
.map(fileResource -> modelMapper.map(fileResource, UploadFile.class))
.orElse(null);
}
book.setCoverImage(coverImage);
book.setContent(bookContent);
book.setTitle(addBookResource.getTitle());
book.setDescription(addBookResource.getDescription());
book.setCategories(Arrays.stream(addBookResource.getCategories())
.map(Category::new)
.collect(Collectors.toSet()));
bookRepository.save(book);
}
}
UploadFileServiceImplementation.class
#Service
public class UploadFileServiceImplementation implements UploadFileService {
private UploadFileRepository uploadFileRepository;
private ModelMapper modelMapper;
#Autowired
public UploadFileServiceImplementation(UploadFileRepository uploadFileRepository, ModelMapper modelMapper){
this.uploadFileRepository = uploadFileRepository;
this.modelMapper = modelMapper;
}
#Transactional
#Override
public Long save(String filename, byte[] data) {
UploadFile uploadFile = new UploadFile();
uploadFile.setFileName(filename);
uploadFile.setData(data);
UploadFile saved = uploadFileRepository.save(uploadFile);
return saved.getId();
}
#Override
public Optional<FileResource> findById(Long id) {
return uploadFileRepository.findById(id)
.map(file -> modelMapper.map(file, FileResource.class));
}
}
EDIT
After a suggested changes I still got an IllegalStateException:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookService': Unsatisfied dependency expressed through field 'uploadFileService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileService': Unsatisfied dependency expressed through field 'modelMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileService': Unsatisfied dependency expressed through field 'modelMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Step 1: Add a #Bean for Model mapper if already not there in main application class or configuration class:
#SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
#Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
Step 2: Here is how you can manage it, please make below chnages in service impl:
#Service("uploadFileService")
public class UploadFileServiceImplementation implements UploadFileService {
#Autowired
private UploadFileRepository uploadFileRepository;
#Autowired
private ModelMapper modelMapper;
//Remove constructure now.
same do for BookServiceImplementation
#Service("bookService")
public class BookServiceImplementation implements BookService {
#Autowired
private BookRepository bookRepository;
#Autowired
private UploadFileService uploadFileService;
#Autowired
private ModelMapper modelMapper;
//remove constructure
Hi i was trying to work over an existing SpringBoot application. I created a service class and tried to autowire it in the existing controller, but when trying to build, its failing saying bean injection failed.
Cause: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'controller': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
com.disooza.www.card.dispenser.service.FilaPartnerService
com.disooza.www.card.dispenser.controller.CardDispenserController.FilaPartnerService;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.disooza.www.card.dispenser.service.FilaPartnerService] 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)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
Following is my controller class:
#Controller
#RequestMapping(value = "/service")
public class CardController {
private static final Logger LOGGER = LoggerFactory.getLogger(CardController.class);
#Autowired
private CardDao dao;
#Autowired
private PaymentService paymentService;
#Autowired
private FilaPartnerService filaPartnerService;
FilaPartnerService is the newly created interface, and rest all autowires are working fine in this controller.
Interesting thing is when I try to place this service class in any other controller it is working fine. Any help over this issue will be appreciated, since I'm stuck with it.
This is my service interface:
#Service
public interface FilaPartnerService {
RetrievePaymentTokenResponse retrieveXXX(SupplierRequest request);
}
This is the implementation class:
#Component
public class FilaPartnerServiceImpl implements FilaPartnerService {
#Autowired
private RestTemplate restTemplate;
#Autowired
private RetrieveRequestBuilder retrieveRequestBuilder;
#Value("${filaPartner.url}")
private String filaServiceUrl;
#Override
public RetrievePaymentTokenResponse retrieveFilaPaymentToken(SupplierTokenRequest request) {
RetrievePaymentTokenResponse tokenResponse = null;
RetrievePaymentTokenRequest paymentServiceRequest = retrievePaymentTokenRequestBuilder.retrievePaymentTokenRequestBuilder(request);
try {
tokenResponse =
restTemplate.postForObject( FilaServiceUrl, paymentServiceRequest, RetrievePaymentTokenResponse.class);
} catch (RestClientException exp) {
//TO-DO return error code
}
return null;
}
}
I have spring-boot-starter-data-jpa and spring-boot-starter-web. I try load List<Project> from mysql using Spring jpa but get bellow BeanCreationException in controller.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.project.data.spring_jpa.ProjectRepository com.project.application.Controller.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.project.data.spring_jpa.ProjectRepository] 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)}
Controller.java:
...
#RestController
public class Controller {
...
#Autowired
private ProjectRepository repository;
private ProjectAccessor projectAccessor = manager.createAccessor(ProjectAccessor.class);
public void setRepository(ProjectRepository repository){
this.repository = repository;
}
#RequestMapping("/test")
#ResponseBody
public List<Project> test() {
System.out.println("mysql test");
return repository.findAll();
}
...
ProjectRepository.java:
public interface ProjectRepository extends CrudRepository<Project, Long>{
List<Project> findAll();
}
Did you write #Repository annotation on ProjectRepository
#Repository
public interface ProjectRepository extends CrudRepository<Project, Long>{
List<Project> findAll();
}
Do make sure you enabled JpaRepository on your configuration using #EnableJpaRepositories
We get this exception usually when we don't specify where to look for the JPA repositories.
So mention #EnableJpaRepositories("your repository package") where you specify #Configuration or #SpringBootApplication.
It will work fine.