vijay kumar
vijay kumar

Reputation: 1

Spring @Bean with different name but same method name throws Bean creation exception

New to spring.
I have defined 2 @Beans with unique names for each but with the same method name. One of the beans are not created and No valid bean exception is thrown.

@Bean("Example.A") 
public ClassA getNewBean() {
   return new ClassA();
}




@Bean("Example.B")
public ClassA getNewBean() {
  return new ClassA();
}

The second Bean is not created and Exception is thrown as no valid bean exists ClassA.

This post has the two beans in different classes, whereas in my case both are within the same @Configuration.

Upvotes: 0

Views: 913

Answers (1)

When you inject by bean name, you can use @Resource:

@Controller
public class MyController {
    @Resource(name = "Example.A")
    private ClassA obj;

    // ...
}

As an aside, beans should be named by Java standard convention.

Upvotes: 1

Related Questions