简体   繁体   English

正确使用@Bean带注释的方法

[英]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. @Bean批注用于为应用程序上下文创建bean,我们可以将逻辑放在其中以创建对象。 But can we call this method manually somewhere in our code, where the reference of the bean being created is not autowired ??? 但是我们可以在代码中的某个地方手动调用此方法吗,其中所创建的bean的引用不是自动装配的? 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 基于XML

If you for any reason don't want to use @Autowired annotation, you can get your hands on ctx.getBean(). 如果出于任何原因不想使用@Autowired注释,可以使用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. @Bean批注创建一个spring托管的bean。 To get a hold of it use @Autowired. 要使用它,请使用@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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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