Вопрос

Previous Problem:

I have an object dependency such as this. A -> B -> C. There are multiple implementations of C. And as a result, there will be multiple instances of A, such that for each implementation for C = A instances. There is only 1 implementation of A. It is not singleton obviously. For the sake of example, C = 5.

Current Solution:

I need a dependency map to define 5 beans, each of type A. This is done using spring and xml based configuration. There would be 5 bean defs for A, 5 bean defs for each of the C implementations. Each of the A bean defs would refer to their own unique implementation of C as a bean.

I am using SOLID OOP approach which involves writing more classes of about 50-150 lines, on average. I am using separation of concerns first. I then associate these classes using dependency inversion. This creates a relation of objects, which of course is a directed acyclic graph based on dependencies.

New problem:

I have mapped all of these kinds of object dependency relations before in spring XML configuration. And it worked out alright. One drawback was that the XML was lengthy, seemed repetitive and XML itself, when representing this kind of relation, isn't very easy to read.

I want to explore mapping these object relations using only annotation configured, but I haven't seen any examples or documentation where it allows me to setup dependency hierarchies.

Это было полезно?

Решение

With the @Qualifier annotation it's possible to inject beans by name, so something like this is possible:

@Configuration
public class ClassCConfig {

    @Bean(name = "c1")
    public C createrC1() {
        returns new C();
    }

    @Bean(name = "c2")
    public C createrC2() {
        ...
    }

    @Bean(name = "c3")
    public C createrC3() {
        ...
    }

    ....   

And then inject hose in different instances of A:

@Configuration
public class ClassAConfig {

    @Autowired
    @Qualifier("c1")
    private C c1;

    @Autowired
    @Qualifier("c2")
    private C c2;

    ...

    @Bean(name = "a1")
    public A createA1() {
        ...
    }

    @Bean(name = "a2")
   public A createA2() {
       ...
   }

With this it's possible to wire any tree of beans using only Java (scanned) configuration.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top