error springboot #autowired dependency - spring

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();
}

Related

NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate

After Upgrading Spring packages from 4.3 to 5.3 I am seeing below error in my service. It was working fine before upgrade
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier("customendpoint")}
Here is sample code
#Configuration
public class HttpServerConfig {
#Autowired
#Qualifier("customendpoint")
private String endpoint;
#Bean(name = "customendpoint")
String getEndpoint() throws IOException {
String enpval = 'hello.world.com'
return enpval;
}
#Bean
public Orchestrator orchestrator() {
Preconditions.checkNotNull(chainHelper);
OrchestratorHelper orchestratorHelper = new OrchestratorHelper(chainHelper, 30_000);
ABCOrchestrator abcOrchestrator = new ABCOrchestrator(orchestratorHelper);
return Orchestrator.builder()
.withDelegate(abcOrchestrator)
.withServiceName(endpoint)
.build();
}
}
}
Upgraded Spring packages to 5 from 4

NoBean found exception

**I am getting below error even though i have down the #autowired .please some one let me know why this issue happening its a ant build with spring config
utor.
2022-07-08 10:18:09,856 WARN org.springframework.context.support.
ClassPathXmlApplicationContext - Exception encountered during context initialization
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor':
Unsatisfied dependency expressed through field 'headerProcessor';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value=headerProcessor)}
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor': Unsatisfied dependency expressed
through field 'headerProcessor';
nested exception is org.springframework.beans.factory.
NoSuchBeanDefinitionException: No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]: expected at least 1 bean which qualifies as
autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value=headerProcessor)}
#Component
public class DelegateProcessor implements ItemProcessor<Object, Object>, InitializingBean {
#Autowired
#Qualifier("headerProcessor")
private ItemProcessor<FileHeader, FileHeader> headerProcessor;
#Autowired
#Qualifier("detailProcessor")
private ItemProcessor<FileDetail, FileDetail> detailProcessor;
#Autowired
#Qualifier("trailerProcessor")
private ItemProcessor<FileTrailer, FileTrailer> trailerProcessor;
#Component
public class HeaderProcessor implements ItemProcessor<Object, Object>{
#Autowired
private HeaderValidatorDao headerValidatorDao ;**
With a configuration class you could initialize your beans manually, specially if they need custom names.
#Configuration
public class MyCustomConfiguration {
#Bean(name ="headerProcessor")
public ItemProcessor<FileHeader, FileHeader> headerProcessorBean() {
ItemProcessor<FileHeader, FileHeader> myBean = new HeaderProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
#Bean(name ="detailProcessor")
public ItemProcessor<FileDetail, FileDetail> detailProcessorBean() {
ItemProcessor<FileDetail, FileDetail> myBean = new ItemProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
}
In this way these beans will be available for autowiring.

Unit Test - No qualifying bean of type ERROR

I am trying to unit test my rest api controller. Controller code is as below
#RestController
#RequestMapping("/events")
public class EventController {
#Autowired
private EventService eventService;
#GetMapping
public Iterable<Event> getEvents(EventSearchFilter filter, #PageableDefault(page = 1, size = 5, sort = "location.city, asc") Pageable pageable) {
return eventService.findEventsOnCondition(filter, pageable);
}
...
}
Test class is
#RunWith(SpringRunner.class)
#WebMvcTest(EventController.class)
public class EventEndpointTest {
private MockMvc mockMvc;
#InjectMocks
private EventController eventController;
#Mock
private EventService eventService;
#InjectMocks
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(eventController).setCustomArgumentResolvers(pageableArgumentResolver).build();
}
#Test
public void getEvents() throws Exception{
Event event = new Event();
event.setName("TestName");
EventSearchFilter filter = new EventSearchFilter();
filter.setName("TestName");
List<Event> eventList = singletonList(event);
given(eventController.getEvents(any(EventSearchFilter.class), any(PageRequest.class))).willReturn(eventList);
mockMvc.perform(get("/events")
.contentType(APPLICATION_JSON))
.andExpect(status().isOk());
}
...
}
However, I got error complaining saying I have Error creating bean with name 'eventController':
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'EventService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}.
As I got above error, I tried use Autowired annotation for my EventService. It still doesn't work. any ideas? Thanks.
I found a solution. All I need to do is replacing #WebMvcTest(EventController.class) in my Test class to #SpringBootTest(classes = Application.class). Thanks guys.
Did you declare #Service annotation at EventService?
#Service
public class EventService {
...something code..
}
I guess Spring cannot find bean named EventService
I had a similar issue where the stack trace showed
java.lang.IllegalStateException: Failed to load ApplicationContext
...
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Controller': Unsatisfied dependency expressed through field 'i18NService';
...
...
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...Service' available:
...
...
...
and ultimately the solution was that the services needed to be mocked with #MockBean since regular components (including services and repositories) will not be scanned.
Same answer with #DFeng. Encountered the below error:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mysqlRedisCachingController': Unsatisfied dependency expressed through field 'mysqlRedisBusinessService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mysqlRedisBusinessService': Unsatisfied dependency expressed through field 'mysqlRedisService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mysqlRedisService': Unsatisfied dependency expressed through field 'mysqlRedisRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.caching.redismanager.repo.MysqlRedisRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.caching.redismanager.repo.MysqlRedisRepository' in your configuration.
This annotation did the trick.
#MockBean
Added the below in the Test Class:
#MockBean
private MysqlRedisRepository mysqlRedisRepository;
#Test
void contextLoads() {}
It works as expected. Hope this helps.

spring retry unit test

I am using spring retry (http://docs.spring.io/spring-retry/docs/1.1.2.RELEASE/apidocs/) in a maven project and I have the following unit test
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class RetriableFileManagerTest {
#Autowired
#Qualifier("asset")
private AssetResource assetResource;
#Test
public void testRetry() throws URISyntaxException {
byte[] image = this.assetResource.fetchResource("name", "path");
verify(assetResource, times(3)).fetchResource("name", "path");
Assert.assertEquals("should be equal", "image", new String(image));
}
#Configuration
#EnableRetry
public static class SpringConfig {
#Bean(name = "asset")
public AssetResource assetResource() throws Exception {
AssetResource remoteService = mock(AssetResource.class);
when(remoteService.fetchResource(anyString(), anyString()))
.thenThrow(new RuntimeException("Remote Exception 1"))
.thenThrow(new RuntimeException("Remote Exception 2"))
.thenReturn("Completed".getBytes());
return remoteService;
}
}
}
However when I try to run the test it fails with
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private ctp.cms.actions.handlers.repository.resources.AssetResource ctp.cms.actions.handlers.filemanager.RetriableFileManagerTest.assetResource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ctp.cms.actions.handlers.repository.resources.AssetResource] 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), #org.springframework.beans.factory.annotation.Qualifier(value=asset)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ctp.cms.actions.handlers.repository.resources.AssetResource] 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), #org.springframework.beans.factory.annotation.Qualifier(value=asset)}
Finally figured out the issue, I had to move the #Retryable annotation to the interface that AssetResource implements and autowire this interface type to the unit test.
Error message says
No qualifying bean of type
[ctp.cms.actions.handlers.repository.resources.AssetResource] found
for dependency
How is ctp.cms.actions.handlers.repository.resources.AssetResource declared?
Do you have #Component (#Service or similar annotation on it?) Is this package enabled for #ComponentScan ?

Could not instantiate bean class: No default constructor found; nested exception is java.lang.NoSuchMethodException

I am trying to #Autowired a class which is a simple class, without Annotations, is just a class which has some calculation. However when I try to #Autowired that class, in my controller I get the following error:
Controller:
#Controller
public class LeituraController extends HemisphereController {
private static final String VIEW = "calculation/index";
#Autowired
private MyClass evapo;
#RequestMapping(value = "/request", method = RequestMethod.GET)
#SuppressWarnings("unchecked")
public ModelAndView leituras() {
ModelAndView view = new ModelAndView(VIEW);
Double valorMax = evapo.calculation();
return view;
}}
Example of class:
public class MyClass {
public Double calculation(){
//implementation
}
}
Error:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.pontoall.hemisphere.core.calculo.evaportranspiracao.MyClass net.pontoall.hemisphere.controller.LeituraController.evapo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [net.pontoall.hemisphere.core.calculo.evaportranspiracao.MyClass] 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:513)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 21 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [net.pontoall.hemisphere.core.calculo.evaportranspiracao.MyClass] 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:948)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:817)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:731)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485)
... 23 more
Anybody could help me? Thanks.
The injected MyClass instance must be a Spring bean. Annotate it with #Component or another bean annotation, or declare it in the spring XML config file.

Resources