简体   繁体   中英

Correct use of the @Bean annotated method

@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

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

@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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM