Spring couldn't create bean of Implemented IgniteRepository - spring-boot

I am using spring boot and Ignite Database
I have created only one Repository and I am setting data in Pojo to save using IgniteRepository
Here are the required dependency for Ignite with Spring: Ignite Version :: 2.0.0
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-core</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-spring</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-indexing</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-spring-data</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.195</version>
</dependency>
Here I am using H2 database dependencies If I don't use it I receive another error which is completely unknown.
IgniteConfiguration :
#Configuration
#EnableIgniteRepositories(excludeFilters = {
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {
TempRepository.class, GarageRepository.class, CarRepository.class,
IncidentRepository.class, MachineRepository.class, MileageRepository.class,
LicenseRepository.class})
})
public class IgniteSpringConfiguration {
#Bean
public Ignite igniteInstance() {
IgniteConfiguration cfg = new IgniteConfiguration();
// Setting some custom name for the node.
cfg.setIgniteInstanceName("eventInsights");
// Enabling peer-class loading feature.
cfg.setPeerClassLoadingEnabled(true);
// Defining and creating a new cache to be used by Ignite Spring Data
// repository.
CacheConfiguration<Long, User> userCacheConfig = new CacheConfiguration<Long, User>("UserCacheConfig");
// Setting SQL schema for the cache.
userCacheConfig.setIndexedTypes(Long.class, User.class);
cfg.setCacheConfiguration(new CacheConfiguration[] {
userCacheConfig,
});
return Ignition.start(cfg);
}
}
UserRepository Interface:
#RepositoryConfig(cacheName = "UserCacheConfig")
public interface UserRepository extends IgniteRepository<User, Long>{
User findByEmail(String email);
}
Now Main Class::
private static UserRepository userRepo;
private static AnnotationConfigApplicationContext ctx;
public static void main(String[] args) {
ctx = new AnnotationConfigApplicationContext();
ctx.register(IgniteSpringConfiguration.class);
ctx.refresh();
userRepo= ctx.getBean(UserRepository.class);
User user=new User();
user.setEmail("george.paul01#xyz.com");
user.setId(1L);
user.setPassword("password");
userRepo.save(user);
User getUser=userRepo.findByEmail("george.paul01#xyz.com");
if(getUser!=null) {
System.out.println(getUser.getEmail());
System.out.println(getUser.getPassword());
}
else {
System.out.println("User name is not found");
}
}
User Pojo:
public class User implements Serializable
{
private static final long serialVersionUID = 1L;
public Long id;
#QuerySqlField(index = true)
private String password;
#QuerySqlField(index = true)
private String email;
//getters and setters method here I am skipping in my question
}
After running I am getting error :
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userRepository': Unsatisfied dependency
expressed through constructor parameter 0; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'java.lang.Class>' available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {} at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at
com.mphasis.springreact.services.admin.AdminController.main(AdminController.java:14)
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'java.lang.Class>' available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {} at
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 13 more

#RepositoryConfig does not declare #Repository or #Component. Guess it doesn't get component scanned. Try:
#Component
#RepositoryConfig(cacheName = "UserCacheConfig")
public interface UserRepository extends IgniteRepository<User, Long>{
User findByEmail(String email);
}

Related

Unsatisfied dependency expressed through field on factory-bean

I am getting the following error :
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'factoryBO': Unsatisfied dependency expressed through field 'cleanupProvider': No qualifying bean of type [com.spring.factory.interfaces.impl.CleanupProvider] found for dependency [com.spring.factory.interfaces.impl.CleanupProvider]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spring.factory.interfaces.impl.CleanupProvider] found for dependency [com.spring.factory.interfaces.impl.CleanupProvider]: 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:350)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.spring.factory.runner.FactoryRunner.main(FactoryRunner.java:10)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spring.factory.interfaces.impl.CleanupProvider] found for dependency [com.spring.factory.interfaces.impl.CleanupProvider]: 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1398)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570)
... 15 more
Source code :
FactoryBo.java
I added #Autowired on top od CleanupProvider class; I did it for corresponding interface as well; But it didn't work for me;
package com.spring.factory.bo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.spring.factory.interfaces.ICleanupProvider;
import com.spring.factory.interfaces.impl.CleanupProvider;
#Component
public class FactoryBO {
#Autowired
CleanupProvider cleanupProvider;
public void getFactoryProviderLogic() {
cleanupProvider.performCleanup("Algo");
}
}
CleanupProvider.java
package com.spring.factory.interfaces.impl;
import com.spring.factory.interfaces.ICleanupProvider;
import com.spring.factory.interfaces.ICleanupStrategy;
public class CleanupProvider implements ICleanupProvider {
#Override
public String performCleanup(String strate) {
System.out.println("Received Text:::"+ strate);
return strate+":"+"Received";
}
#Override
public void registerStrategy(ICleanupStrategy normalizeStrategy) {
System.out.println("NormalizationProvider:::registerStrategy::");
}
}
CleanupProviderFactory .java
So, here I want to make the existing method createInstance as a factory method;
package com.spring.factory.interfaces.impl;
import com.spring.factory.interfaces.ICleanupProvider;
import com.spring.factory.interfaces.ICleanupProviderFactory;
public class CleanupProviderFactory implements ICleanupProviderFactory {
public ICleanupProvider createInstance() {
ICleanupProvider normalizeProvider = new CleanupProvider();
normalizeProvider.registerStrategy(new CleanupStrategy());
return normalizeProvider;
}
public static ICleanupProviderFactory createFactoryInstance() {
return new CleanupProviderFactory();
}
}
ICleanupProvider.java
package com.spring.factory.interfaces;
public interface ICleanupProvider {
public String performCleanup(String algo);
public void registerStrategy(ICleanupStrategy strategy);
}
ICleanupProviderFactory.java
package com.spring.factory.interfaces;
public interface ICleanupProviderFactory {
}
package com.spring.factory.runner;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.factory.bo.FactoryBO;
public class FactoryRunner {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
FactoryBO bo = context.getBean(FactoryBO.class);
bo.getFactoryProviderLogic();
context.close();
}
}
spring.xml
<context:annotation-config/>
<context:component-scan base-package="com.spring.factory.bo"></context:component-scan>
<bean id="cleanupProviderFactory"
class="com.spring.factory.interfaces.impl.CleanupProviderFactory"
factory-method="createFactoryInstance"></bean>
<bean id="cleanupProvider"
class="com.spring.factory.interfaces.ICleanupProvider"
factory-bean="cleanupProviderFactory" lazy-init="default" factory-method="createInstance"></bean>
Is there anything I missed?
You can add #Component to your CleanupProvider class:
#Component
public class CleanupProvider { ...}
Or define a method to create your been like so:
#Bean
public CleanupProvider getCleanupProvider() {
return new CleanupProvider();
}
An explanation of which annotation to use is best described here: Understanding Spring #Autowired usage
I believe you just missed providing your CleanupProvider class a #Bean annotation (like #Component, #Service, #Repository, #Controller) so that bean factory recognizes it and is able to Autowire, like this Spring documentation tells you to do so.
EDIT
Ok, so have seen your spring.xml, I assume the mistake was you were declaring the bean as ICleanupProvider class, which is the interface, whereas FactoryBO autowires the implementation (CleanupProvider).

Setting up a 2nd Springboot application to use a #Autowired repository #Component from App 1 caused incorrect loading and REST requests broke

I have setup 2 Spring Boot applications. I am trying to #Autowire the repository from Application 1 in Application 2.
Both of these applications will be using REST to communicate back and forth. When I ran application 2 alone without the #Autowire of the repository for Application 1 I could correctly communicate with http://localhost:8082/runTestExecution via the #RestController HomeController class without an issue.
When I setup the #Autowire and #ComponentScan({"com.miw.mcb.server.repositories"}) so that I have access to the repositories of Application 1, Application 2 no longer functions correctly.
I am unable to reach the #RestController at http://localhost:8082/runTestExecution.
I also had a class which implemented CommandLineRunner which would run when I started up Spring Boot and this no longer runs either.
#Component
public class InitialRunner implements CommandLineRunner
Is this a issue because Application 1 also has a main class which loads #SpringBootApplication?
Can anyone suggest what is going wrong?
Below I have outlined my steps I took to add the jar of Application 1 and #Autowired class to Application 2
Here are the steps I took:
Setup maven to have the new library dependency and add it to the maven library mvn:install
Add Autowired bean to the HomeController class:
#RestController
public class HomeController {
#Autowired
TestSuiteRepository repo;
#RequestMapping(value = "/")
public String index() {
return "index";
}
#RequestMapping("runTestExecution")
public String runTestExecution(#RequestParam(value = "testExecutionID", required = true) String testExecutionID) {
return "Good";
}
}
Main class
#SpringBootApplication
public class AdbService {
public static void main(String[] args) {
SpringApplication.run(AdbService.class, args);
}
TestResultRepository class
package com.miw.mcb.server.repositories;
#Component
public interface TestResultRepository extends PagingAndSortingRepository<TestResult, Long> {
}
Add #Configuration and #ComponentScan, only supply the comment scan for the repositories package of the JAR file
Application 2 main class
#Configuration
#ComponentScan({"com.miw.mcb.server.repositories"})
#SpringBootApplication
public class AdbService {
public static void main(String[] args) {
SpringApplication.run(AdbService.class, args);
}
}
Application 1 Config Class
#Configuration
#ComponentScan({"com.miw.mcb.server.repositories"})
public class AppConfig {
}
Application 1 Main class
#SpringBootApplication
public class ReactAndSpringDataRestApplication {
public static void main(String[] args) {
SpringApplication.run(ReactAndSpringDataRestApplication.class, args);
}
}
Prior to adding the #ComponentScan I got the following stack trace:
2016-04-14 13:29:56 - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'homeController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.miw.mcb.server.repositories.TestSuiteRepository
com.miw.mcb.adbservice.HomeController.repo; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.miw.mcb.server.repositories.TestSuiteRepository] 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)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
at
org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
at com.miw.mcb.adbservice.AdbService.main(AdbService.java:38) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:478)
at java.lang.Thread.run(Thread.java:745)
Try to use #EnableJpaRepositories instead of #ComponentScan for JpaRepositories:
#Configuration
//#ComponentScan({"com.miw.mcb.server.repositories"})
#EnableJpaRepositories("com.miw.mcb.server.repositories")
#SpringBootApplication
public class AdbService {
public static void main(String[] args) {
SpringApplication.run(AdbService.class, args);
}
}

error springboot #autowired dependency

I try do a fill repository with metrics in spring boot, but I have the problem that when I execute I recive error.
This is my error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'actuatorMetricsPrinter' defined in file [ActuatorMetricsPrinter.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.util.Collection]: : No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1115)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at hello.Application.main(Application.java:14)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1118)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:919)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:811)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:739)
... 18 common frames omitted
And this is my code when I recive error:
#Autowired
public DummyController(ActuatorMetricsPrinter metricsPrinter) {
this.metricsPrinter = metricsPrinter;
}
I have a class ActuatorMetricsPrinter that show the metrics but I have a problem when try fill this repository
*EDIT *
#Component
public class ActuatorMetricsPrinter {
private MetricRepository repository;
private static final String TEMPLATE = "Metric: %s [%s]";
private Collection<PublicMetrics> publicMetrics = null;
public String printAllMetrics() {
StringBuilder sb = new StringBuilder();
for (PublicMetrics pm : publicMetrics) {
sb.append("Public Metric: " + pm.getClass().getName());
sb.append("\n\n");
for (Metric<?> m : pm.metrics()) {
sb.append(String.format(TEMPLATE, m.getName(), m.getValue().toString()));
sb.append("\n");
}
}
return sb.toString();
}
#Autowired
public void MetricExporterService(MetricRepository repository) {
this.repository = repository;
}
And
#Controller
public class DummyController {
private final ActuatorMetricsPrinter metricsPrinter;
#Autowired
public DummyController(ActuatorMetricsPrinter metricsPrinter) {
this.metricsPrinter = metricsPrinter;
}
#RequestMapping(value = "/customMetrics", method = RequestMethod.GET)
#ResponseBody
public String printMetrics() {
return metricsPrinter.printAllMetrics();
}
#Bean
public ActuatorMetricsPrinter publicMetrics() {
return new ActuatorMetricsPrinter();
}
}
Thank you very much!
Spring beans factory not found a bean Collection<PublicMetrics> publicMetrics for autowarid; try to create a list of PublicMetrics
see : Spring autowire a list
Auto-wiring a List using util schema gives NoSuchBeanDefinitionException
In your case the actual problem is initializing the constructor for ActuatorMetricsPrinter. You have it Autowired to take in a Collection so Spring is trying to find the set of PublicMetrics beans to use as a collection and it cannot find any. Here is the error in what you provided above that points to that. I ran into the same issue myself at one point.
No qualifying bean of type
[org.springframework.boot.actuate.endpoint.PublicMetrics] found for
dependency [collection of
org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at
least 1 bean which qualifies as autowire candidate for this
dependency.
From the Spring Docs on Autowired:
In case of a Collection or Map dependency type, the container will
autowire all beans matching the declared value type. In case of a Map,
the keys must be declared as type String and will be resolved to the
corresponding bean names.
Since the PublicMetrics are not declared as beans I think the right way to do it is by autowiring to a MetricRepository. See this link and the Exporting Metrics section there as a reference. There is a link to a sample application. Here is some modified code that you can use.
#Autowired
public MetricExporterService(MetricRepository repository) {
this.repository = repository;
}
public String printAllMetrics() {
StringBuilder sb = new StringBuilder();
for (Metric metric : repository.findAll()) {
sb.append(String.format(TEMPLATE, metric.getName(), metric.getValue().toString()));
}
return sb.toString();
}

spring boot repository metrics

I am trying to make an object repositoryMetrics in SpringBoot and later I obtained information with this repository. But I create a repository and this always is null.
How I generate a repository and this save the metrics?
I have this code:
public static void stateSist() throws Exception {
InMemoryMetricRepository metricRepository = null;
metricRepository.findAll();
System.out.println(metricRepository.count());
}
EDIT 1:
I do this change in my version and I obtained this error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'actuatorMetricsPrinter' defined in file [ActuatorMetricsPrinter.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.util.Collection]: : No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1115)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at hello.Application.main(Application.java:14)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1118)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:919)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:811)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:739)
... 18 common frames omitted
Thank you!
In order to access all Public Metrics printed by the Spring Boot actuator framework you need to inject a 'Collection' into your component and then access it to read all the metrics. Here is an example:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.stereotype.Component;
import java.util.Collection;
#Component
public class ActuatorMetricsPrinter {
private static final String TEMPLATE = "Metric: %s [%s]";
private final Collection<PublicMetrics> publicMetrics;
#Autowired
public ActuatorMetricsPrinter(Collection<PublicMetrics> publicMetrics) {
this.publicMetrics = publicMetrics;
}
public String printAllMetrics() {
StringBuilder sb = new StringBuilder();
for (PublicMetrics pm : publicMetrics) {
sb.append("Public Metric: " + pm.getClass().getName());
sb.append("\n\n");
for (Metric<?> m : pm.metrics()) {
sb.append(String.format(TEMPLATE, m.getName(), m.getValue().toString()));
sb.append("\n");
}
}
return sb.toString();
}
}
If you want to reproduce this simple scenario, then:
Go to http://start.spring.io/ and create new project with Actuator and Web checked,
Create a demo project with Build tool of your choice (Gradle, Maven),
Download it and open in your IDE,
Create a new component just like one in my example,
Create a new RestController, like this:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class DummyController {
private final ActuatorMetricsPrinter metricsPrinter;
#Autowired
public DummyController(ActuatorMetricsPrinter metricsPrinter) {
this.metricsPrinter = metricsPrinter;
}
#RequestMapping(value = "/customMetrics", method = RequestMethod.GET)
public String printMetrics() {
return metricsPrinter.printAllMetrics();
}
}
Then start the application and type in your browser: http://localhost:8080/customMetrics
You should see all the metrics printed by your class in the most messy way possible
If you are using Maven or Gradle for dependency management, then you must make sure these are present in either (from Spring Clouds's Home Page):
Maven:
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Angel.SR4</version>
</parent>
<dependencies>
<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>
</dependencies>
Gradle:
buildscript {
dependencies {
classpath "io.spring.gradle:dependency-management-plugin:0.4.0.RELEASE"
}
}
apply plugin: "io.spring.dependency-management"
dependencyManagement {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-starter-parent:Angel.SR4'
}
}
dependencies {
compile 'org.springframework.cloud:spring-cloud-starter-config'
compile 'org.springframework.cloud:spring-cloud-starter-eureka'
}
If you omit the parent in Maven or the dependencyManagement in gradle, and try to just import the latest version of each of the dependencies, you will get the runtime error that you are describing.
A similar problem addresses this here on GitHub.

How to Spring 3.2 + hibernate 4 on javaconfig correctly

I want to make test in Spring 3.2 + Hibernate 4 + javaconfig
Content of build.gradle is the next:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9'
}
}
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'tomcat'
ext.springVersion = '3.2.4.RELEASE'
ext.springMobileVersion = '1.1.0.RELEASE'
ext.thymeleafVersion = '2.0.19'
ext.aspectJVersion = '1.6.9'
ext.cglibVersion = '2.2'
ext.slf4jVersion = '1.6.1'
ext.servletJstlVersion = '1.2'
ext.servletApiVersion = '3.0.1'
ext.servletJspVersion = '2.1'
ext.junitVersion = '4.11'
ext.tomcatVersion = '7.0.42'
ext.pgsqlVersion = '9.1-901.jdbc4'
ext.mockiteoCoreVersion = '1.9.5'
ext.mailVersion = '1.4.7'
ext.dataBindVersion = '2.2.3'
ext.hbVersion = '4.2.7.Final'
ext.guavaVersion = '15.0'
ext.javassistVersion = '3.18.0-GA'
war {
webInf {
include "src/main/webapp/resources/**"
}
}
dependencies {
compile("org.springframework:spring-context:$springVersion") {
exclude module: 'commons-logging'
}
compile "org.springframework:spring-context-support:$springVersion"
compile "org.springframework:spring-web:$springVersion"
compile "org.springframework:spring-webmvc:$springVersion"
compile "org.springframework.mobile:spring-mobile-device:$springMobileVersion"
compile "org.springframework:spring-tx:$springVersion"
compile "org.springframework:spring-orm:$springVersion"
compile "com.fasterxml.jackson.core:jackson-databind:$dataBindVersion"
compile "javax.mail:mail:$mailVersion"
compile "org.thymeleaf:thymeleaf-spring3:$thymeleafVersion"
compile "org.aspectj:aspectjrt:$aspectJVersion"
compile "cglib:cglib-nodep:$cglibVersion"
compile "javax.inject:javax.inject:1"
compile "org.slf4j:slf4j-api:$slf4jVersion"
compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"
compile "org.slf4j:slf4j-log4j12:$slf4jVersion"
compile "javax.servlet:jstl:$servletJstlVersion"
providedCompile("javax.servlet:javax.servlet-api:$servletApiVersion")
providedCompile("javax.servlet.jsp:jsp-api:$servletJspVersion")
// Persistence
compile "postgresql:postgresql:$pgsqlVersion"
compile "org.hibernate:hibernate-core:$hbVersion"
compile "org.hibernate:hibernate-entitymanager:$hbVersion"
compile "org.apache.tomcat:tomcat-dbcp:$tomcatVersion"
compile "org.javassist:javassist:$javassistVersion"
// Tools
compile "com.google.guava:guava:$guavaVersion"
// TEST
testCompile "junit:junit:$junitVersion"
testCompile "org.mockito:mockito-core:$mockiteoCoreVersion"
testCompile "org.springframework:spring-test:$springVersion"
testCompile "org.hamcrest:hamcrest-core:1.3"
testCompile "org.hamcrest:hamcrest-library:1.3"
testCompile "org.apache.commons:commons-lang3:3.1"
// TOMCAT
tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion")
tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") {
exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
}
}
repositories {
mavenCentral()
maven { url 'http://repo.spring.io/libs-release' }
}
task wrapper(type: Wrapper) {
gradleVersion = '1.8'
}
PersistenceConfig content is the next:
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:pgsql.properties" })
#ComponentScan(basePackages = {"com.example.persistence"})
public class PersistenceConfig
{
#Autowired
private Environment env;
#Bean
public DataSource dataSource()
{
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory()
{
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.example.persistence.domain" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager()
{
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
{
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
setProperty("hibernate.globally_quoted_identifiers", "true");
}
};
}
}
ProductServiceTest content is the next:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {PersistenceConfig.class})
public class ProductServiceTest
{
private static final Logger LOG = LoggerFactory.getLogger(ProductServiceTest.class);
#Autowired
private ProductService productService;
#Autowired
private ApplicationContext applicationContext;
#Test
public final void listApplicationBeans() throws Exception
{
List<String> beans = Arrays.asList(applicationContext.getBeanDefinitionNames());
for (String bean: beans)
{
LOG.info(String.format("--> App Beans [%s]", bean));
}
}
}
persistence.properties content is the next:
# jdbc
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://some_address:5432/some_database
jdbc.user=someuser
jdbc.pass=somepassword
# hibernate
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
Product content is the next:
#Entity
public class Product implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name) {
this.name = name;
}
public Product(String name)
{
setName(name);
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append(Product.class.getSimpleName()).append(" [\n");
builder.append("id = ").append(id).append("\n");
builder.append("name = ").append(name).append("\n");
builder.append("]");
return builder.toString();
}
}
ProductDao content is the next:
import org.springframework.stereotype.Repository;
import com.example.persistence.dao.common.AbstractDao;
import com.example.persistence.domain.Product;
#Repository
public class ProductDao extends AbstractDao<Product>
{
public ProductDao()
{
super();
setClazz(Product.class);
}
}
ProductService content is the next:
#Service
public class ProductService extends AbstractService<Product>
{
#Autowired
private ProductDao dao;
public ProductService()
{
super();
}
#Override
protected IOperation<Product> getDao()
{
return dao;
}
}
Result of gradle clean test:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.persistence.dao.impl.ProductDao com.example.persistence.service.impl.ProductService.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.persistence.dao.impl.ProductDao] 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:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 44 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.persistence.dao.impl.ProductDao com.example.persistence.service.impl.ProductService.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.persistence.dao.impl.ProductDao] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 60 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.persistence.dao.impl.ProductDao] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 62 more
According to the stacktrace:
Could not autowire field: private com.example.persistence.dao.impl.ProductDao
com.example.persistence.service.impl.ProductService.dao; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
When I found such issue I eliminate the following:
The bean is not annotated or not covered by component scan.
You defined
#ComponentScan(basePackages = {"com.example.persistence"})
It covers your package com.example.persistence.dao.impl.ProductDao
Look’s fine here.
Make sure annotations are correct: ProductDao is annotated #Repository
Looks ok.
Make sure that com.example.persistence.dao.impl.ProductDao is in the classpath.
You are executing the command gradle clean test, which means your code will be compiled before test execution (as test depend on the compile task).
If it compiles I guess that ProductDao is in your classpath
Make sure that the JUnit has the required configuration for bootstrapping
spring application context.
#ContextConfiguration
class points to your configurations class.
loader attribute was not defined so spring will use the default DelegatingSmartContextLoader (no #WebAppConfiguration in your configuration and version >3.2).
Looks good to me.
Unfortunately I cannot find any issue and everything looks fine (I hope this check list will help someone).
So I would guess that the issue is somewhere in the missing details; like you have to class of ProductDao under different packages and you are using the wrong one in the ProductService or the wrong interface etc.
Hope this helps
I share with you an example of my Hibernate java configuration.
I hope you love it:
Pre-requirement: pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.6.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.9.Final</version>
</dependency>
<!-- POSTGRESQL -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
</dependencies>
Step 1: application.properties
################### DataSource Configuration ##########################
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost/curso_db
jdbc.username=alumno
jdbc.password=alumno
#################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
packagesToScan=com.curso.online.model
Step 2: Config.java
package com.curso.online;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#PropertySources(value = { #PropertySource("classpath:/application.properties") })
#ComponentScan(basePackages = "com.curso.online")
public class Config {
#Value("${jdbc.driverClassName}")
private String KEY_DRIVER_CLASS;
#Value("${jdbc.url}")
private String KEY_JDBC_URL;
#Value("${jdbc.username}")
private String KEY_JDBC_USERNAME;
#Value("${jdbc.password}")
private String KEY_JDBC_PASSWORD;
#Value("${hibernate.dialect}")
private String KEY_HIBERNATE_DIALECT;
#Value("${hibernate.show_sql}")
private String KEY_HBERNATE_SHOW_SQL;
#Value("${packagesToScan}")
private String KEY_ENTITIES_PKG;
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(dataSource());
factory.setPackagesToScan(KEY_ENTITIES_PKG);
factory.setHibernateProperties(hibernateProperties());
return factory;
}
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", KEY_HIBERNATE_DIALECT);
properties.setProperty("hibernate.show_sql", KEY_HBERNATE_SHOW_SQL);
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(
SessionFactory sessionFactory) {
return new HibernateTransactionManager(sessionFactory);
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(KEY_DRIVER_CLASS);
dataSource.setUrl(KEY_JDBC_URL);
dataSource.setUsername(KEY_JDBC_USERNAME);
dataSource.setPassword(KEY_JDBC_PASSWORD);
return dataSource;
}
}
I came across a similar problem with my Spring Hibernate project in my test suites.
The only way I could solve the problem was to autowire the class by using its super class as its type (AbstractService in your case) and then use a #Qualifier to tell Spring which child class I am referring to. It will look something like this in your case:
#Qualifier("ProductService")
#Autowired
private AbstractService productService;
It is painful as then in the test function you have to cast productService object to ProductService every time you use a method that belongs to the child class. So if you have already solved this using another solution please share it with us.

Resources