1
votes

I am new to Springs so please don't mind if my question is dumb

I have a class which implements two interfaces

public class AAA implements BBB, CCC {

}

public interface BBB {
  void method BBB_method();
}


public interface CCC {
  void CCC_method();
}

I am defining bean object in Context class as follows:

public class Context {

   @Bean
   public BBB myObject(){
       return new AAA();
   }

   @Bean
   public CCC myObject(){    //Issue is here
        return new AAA();    //Duplicate API name not allowed
   }
}

I have autowired the beans in 2 different class as follows:

@Autowired
private BBB myObject;

@Autowired
private CCC myObject;

What should be the best way to autowire this and define the bean in the Context class? And does defining 2 bean object in Context.java make sense? How to resolve this situation where I want my bean to be autowired to two different interfaces ( and object name being the same..as in my case its myObject) ? Your response is very much appreciated. Thank You !

2

2 Answers

0
votes

One point you have missed is that you don't need the method names same as the reference variable names i.e, you don't need your method name as myObject.

Spring container simply tries to find the implementation classes for the dependencies and if they are found, they will be injected on to the Autowired fields (reference variable names doesn't matter, just their types i.e., class names matter).

In your Context class, you can't define two methods with the same signature, so change them to names like shown below:

public class Context {

   @Bean
   public BBB bObject(){
       return new AAA();
   }

   @Bean
   public CCC cObject(){   
        return new AAA(); 
   }
}
0
votes

Spring resolves beans by their names, because during runtime it couldn't fetch method return type from you bean declaration.

So the best way to solve your problem - just specify different bean declaration methods names (bbbObject and cccObject for example)

when autowiring if there is ambiguaty and spring couldn't resolve it by default specify bean name using Qualified annotation.