是否有必要在@Configuration类中自动装配@Bean以在该类中使用?

时间:2016-10-12 11:19:43

标签: java spring spring-bean

在具有@Configuration注释的类中,其具有带@Bean注释的方法,是否必须具有与bean同名的@Autowired字段才能在同一个班级中使用它?由于配置类创建了bean,它是否应该通过直接调用方法立即访问它?

例如:

@Configuration
public class ConfigClass
{
    @Autowired
    private BeanForSomething beanForSomething;

    @Bean
    public BeanForSomething beanForSomething()
    {
        return new BeanForSomething();
    }

    private void methodThatUsesBean()
    {
        beanForSomething.doSomething();
    }
}

是否可以省略@Autowired字段并只调用beanForSomething().doSomething();来使用bean?也许我误解了@Bean注释的用法。

2 个答案:

答案 0 :(得分:0)

不,@Bean声明已经解决了这个问题。您只需在beanForSomething()

中致电methodThatUsesBean()即可

答案 1 :(得分:0)

正如之前的回答者所说,你可以使用

private void methodThatUsesBean()
{
    beanForSomething().doSomething();
}

但是在另一个bean创建的情况下,您可以使用方法参数

@Bean
public BeanForSomething beanForSomething()
{
    return new BeanForSomething();
}

@Bean
public SecondBean secondBean(BeanForSomething beanForSomething)
{
     return new SecondBean(beanForSomething);
}