0

I am new to the spring and got stuck on some point as explained below -

I have a class color with two different implementation name as Red and Blue and I would like to inject both into the List of color using @inject.

Below is my ApplicationConfiguration class 

package org.arpit.java2blog.config;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.inject.Inject;

import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(CountryConfig.class)
public class ApplicationConfiguration {

    @Inject
    private List<Color> colorList;

    @Bean
    public List<Color> colorList() {
        System.out.println("Second");
        List<Color> aList = new ArrayList<Color>();
        aList.add(new Blue());
        return aList;
    }

}

but getting exception as

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.List org.arpit.java2blog.config.ApplicationConfiguration.colorList; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.arpit.java2blog.config.Color] found for dependency [collection of org.arpit.java2blog.config.Color]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}

A Sdi
  • 665
  • 2
  • 10
  • 24
CoreThought
  • 113
  • 6
  • 16

1 Answers1

1

The correct way to populate your colorList using @Inject is shown in the below code with inline comments:

@Configuration
@Import(CountryConfig.class)
public class ApplicationConfiguration {

    @Inject
    private List<Color> colorList;

    @Bean
    public Color color() {
      return new Blue();//injects Blue object to colorList
    }

    @Bean
    public Color color() {
      return new Red();//injects Red object to colorList
    }
}

Also, you can very well use @Order to inject Color object at a specific index of colorList inside as explained in the Spring doc here.

The solution is working fine, if I remove @component annotation from both the classes red and blue and only provide one bean type after removing component

When you mark your bean classes with @Component (infact for any Spring stereotype annotations), the beans will become eligible for injection and will be automatically loaded into your colorList. So when you provide @Bean annotation method and giving one more object then that also will be added to the list, but in general, you will load the list either using @Component or using @Bean, but not both.

Vasu
  • 21,832
  • 11
  • 51
  • 67