[英]Is it necessary in a @Configuration class to autowire an @Bean for use in that class?
In a class with the @Configuration
annotation, that has a method with the @Bean
annotation, is it necessary to have an @Autowired
field of the same name as the bean in order to use it within this same class? 在带有@Configuration
批注的类中,该类具有带有@Bean
批注的方法,是否有必要具有与Bean同名的@Autowired
字段,以便在同一类中使用它? Since the configuration class created the bean, should it not have immediate access to it by calling the method directly? 既然配置类创建了Bean,那么是否应该不通过直接调用该方法立即访问它?
Eg: 例如:
@Configuration
public class ConfigClass
{
@Autowired
private BeanForSomething beanForSomething;
@Bean
public BeanForSomething beanForSomething()
{
return new BeanForSomething();
}
private void methodThatUsesBean()
{
beanForSomething.doSomething();
}
}
Is it not possible to leave out the @Autowired
field and just call beanForSomething().doSomething();
是否有可能忽略@Autowired
字段并仅调用beanForSomething().doSomething();
to use the bean? 用豆子? Perhaps I'm misunderstanding the usage of the @Bean
annotation. 也许我误解了@Bean
批注的用法。
No, the @Bean
declaration already takes care of that. 不, @Bean
声明已经解决了这一问题。 You just need to call beanForSomething()
in methodThatUsesBean()
您只需要在beanForSomething()
中调用beanForSomething()
methodThatUsesBean()
As previous answerer said, you can use 如先前的回答者所说,您可以使用
private void methodThatUsesBean()
{
beanForSomething().doSomething();
}
But in case of another bean creating you can use method parameter 但是,如果要创建另一个bean,则可以使用method参数
@Bean
public BeanForSomething beanForSomething()
{
return new BeanForSomething();
}
@Bean
public SecondBean secondBean(BeanForSomething beanForSomething)
{
return new SecondBean(beanForSomething);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.