0

@Bean annotation is used to create beans for the application context, we can put the logic inside it to create an object. But can we call this method manually somewhere in our code, where the reference of the bean being created is not autowired ??? I can call this method, but is it a good practice ? If I am calling this then does that not mean that I have not designed my class dependencies correctly ??

Can someone please share their thoughts on this ?

Thanks,

Amar

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Amar Dev
  • 1,360
  • 2
  • 18
  • 38
  • Are you asking how to create a spring managed bean outside xml or java config? –  May 12 '16 at 13:30
  • 1
    Don't call `@Bean` annotated methods from something else then `@Configuration` classes... – M. Deinum May 12 '16 at 13:31
  • @RC. yes, lets say I am calling a method. Inside that method, I need that bean, can I call this method there ? – Amar Dev May 12 '16 at 13:33
  • @M.Deinum "@Configuration" can be used for methods as well, right ?? I created @Bean@Configuration public beanname() {return new ...;} . I am not too sure if what I have written is right – Amar Dev May 12 '16 at 13:40
  • No, this is *not* good practice. Instead of calling `@Bean` methods manually, change your code so that you can access the `ApplicationContext` wherever you need to do this, and then lookup the bean in the `ApplicationContext` - or better, let Spring inject it. – Jesper May 12 '16 at 13:42
  • No don't do that either... Use dependency injection and inject the beans you need. Don't try to obtain a context and do lookups... – M. Deinum May 12 '16 at 13:43

2 Answers2

0

@Bean annotation creates a spring managed bean. To get a hold of it use @Autowired.

If you need access to the object somewhere you cannot autowire it, then generally you should consider redesigning your code.

But if you insist, you will either have to manually create your object, or programatically fetch it from the application-context.

Something like this should work:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("someName");
dd-developer
  • 101
  • 1
  • 8
0

You always have two options:

  1. Annotation based
  2. XML based

If you for any reason don't want to use @Autowired annotation, you can get your hands on ctx.getBean().

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("beanName");

You can read about this holly war here

Community
  • 1
  • 1
ottercoder
  • 852
  • 1
  • 12
  • 31