0

Duplicate:

As the refernece said, I mixed up @Component and @Bean. However, the reference does not answer my question.


Is there a way to have Spring components be created dynamically in a kind of pre-processing step?

Current implementation:

@Component
public interafce MyComperator {
    public bool compare(Object o1, Object o2);
}

@Autowired
List<MyComperator> finalList;

We have different classes implementing this interface and get our finalList containing a component for each class.

Problem:

We now want to use this idea in a pre-processing step. The code should look something like this:

@Component
public interafce MyComperator {
    public bool compare(Object o1, Object o2);
}

@Component
public interafce MyStringComperator {
    public bool compareString(String s1, String s2);
}

//Possible?
@Component
public class ComponentFactory {

    @Autowired
    List<MyStringComperator> stringList;

    List<Component> makeComperator() {
        List<Component> list;
        for (MyStringComparator com : stringList) {
            list.add(new MyComperator() {
                         // use com.compareString(...) internally
                         }
                    )
        }    
        return list;
    }
}

@Autowired
List<MyComperator> finalList;

We want classes implementing the ´MyStringComperator´ to be collected in the factory and then create a ´MyComerator´ for each ´MyStringComperator´.

Is this possible?

2
  • You can use @PostConstruct in BeanFactory#makeComperator() method. Commented Aug 5, 2019 at 12:07
  • @Configuration and @Bean are what you are looking for. Commented Aug 5, 2019 at 12:07

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.