Chowdary Bobby
Chowdary Bobby

Reputation: 57

how do we load particular class dynamically using dependency injection in spring?

how do we load particular class dynamically using dependency injection in spring?

Upvotes: 3

Views: 725

Answers (2)

Paul
Paul

Reputation: 20061

While Tom Sebastian's answer is correct it can be improved (I ran out of space in the comment block to explain the improvements).

The convention when using @Bean is to omit "get" from the method name. This is because configuration classes use a method's name as the bean name. In your @Configuration-annotated class declare the beans like this:

@Bean
public Operator airtel()
{
  return new Airtel();
}

@Bean
public Operator idea() 
{
  return new Idea();
}

To inject your beans use @Resource rather than @Autowired as recommended in the Spring reference doc:

If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation...

@Resource(name="airtel")
private Operator airtel;

@Resource(name="idea")
private Operator idea;

As it turns out the name of the @Resource isn't required here...I included it above to demonstrate how it's used. If the name of the field is the same as the name of the bean (which in this example is the method name in the @Configuration-annotated class) then name is not required:

@Resource
private Operator airtel;

@Resource
private Operator idea;

As I said, Tom's answer is correct; I wanted to expand it a little with slightly more advanced details.

Upvotes: 1

Tom Sebastian
Tom Sebastian

Reputation: 3433

You can create @Bean with names like:

@Bean(name={"airtel"})
 public Operator getOperator1() {  
  return new Airtel();
 }

@Bean(name={"idea"})
 public Operator getOperator2() {  
  return new Idea();
 }

and Autowire them with @Qualifier

@Autowired
@Qualifier("airtel")
private Operator airtel;

@Autowired
@Qualifier("idea")
private Operator idea;

Upvotes: 4

Related Questions