0

I have problem with NoSuchBeanDefinitionException.

@Component
public class Monitor {

    private List<String> urlsToCheckState;

    @Autowired
    ServerConfig config; 

    public Monitor(config config, List<String> urlsToCheckState){
       urlsToCheckState.add("state1");
    }

I understand that Spring can not find Bean which return list of String. I was looking for solution but coudn't find anything which solve my problem. Here is my error.

Error creating bean with name 'Monitor' defined in file [C:\Users]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

vinS
  • 1,417
  • 5
  • 24
  • 37
Tom
  • 303
  • 1
  • 4
  • 18

2 Answers2

0

Because you have not used @Autowired on urlsToCheckState. You have to inject it using constructor injection.

Inside your component create a constructor as below:-

Monitor(List<String> urlsToCheckState){
   this.urlsToCheckState = urlsToCheckState;
}

This way you would be able to inject using constructor.

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
  • Unfortunately it didn't help - `Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [Monitor]: No default constructor found; nested exception is java.lang.NoSuchMethodException: Monitor.()` then I added deafult constructor and have another exception `java.lang.NullPointerException: null at Monitor.(Monitor.java:135) ~[classes/:na]` – Tom Apr 12 '18 at 10:18
  • okay! Have you declared List urlsToCheckState as a bean anywhere in a config file. Because looks like you haven't declared a bean anywhere? – Vinay Prajapati Apr 12 '18 at 10:22
  • I did not. When I was looking for an answer I saw some information that I should declared List of String in config file but I do know how and where should I make it – Tom Apr 12 '18 at 10:24
0

To have dependencies injected at construction you need to have your constructor marked with the @Autowired annoation like below.

@Autowired
Monitor(List<String> urlsToCheckState){
   this.urlsToCheckState = urlsToCheckState;
}

Of course before injection you must create instance of bean urlsToCheckState.

Bartek M.
  • 26
  • 5