CommandLineRunner和Beans(Spring)

8

我的问题所涉及的代码:

   @SpringBootApplication
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public Object test(RestTemplate restTemplate) {
        Quote quote = restTemplate.getForObject(
                "http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
        log.info(quote.toString());
        return new Random();
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            Quote quote = restTemplate.getForObject(
                    "http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
            log.info(quote.toString());
        };
    }
}

我对Spring很陌生。据我所知,@Bean注解负责将对象保存在IoC容器中,是这样吗?
如果是这样的话:首先收集所有带有@Bean注解的方法,然后再执行它们吗?
在我的示例中,我添加了一个名为test()的方法,它与run()执行相同的操作,但返回一个对象(Random())。
结果相同,因此它可以使用CommandLineRunner和Object一起工作。
是否有理由返回CommandLineRunner,例如使用类似run()的语法?
此外:在这一点上,我还没有看到将方法移动到容器中的优势。为什么不直接执行它呢?
谢谢!
1个回答

14
@Configuration类(@SpringBootApplication扩展了@Configuration)是注册Spring beans的地方。 @Bean用于声明一个Spring bean。带有@Bean注解的方法必须返回一个对象(即bean)。默认情况下,Spring beans是单例的,因此一旦带@Bean注解的方法被执行并返回其值,该对象将一直存在到应用程序结束。

在您的情况下

    @Bean
    public Object test(RestTemplate restTemplate) {
        Quote quote = restTemplate.getForObject(
                "http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
        log.info(quote.toString());
        return new Random();
    }

这将创建一个名为“test”的Random类型的单例bean。 因此,如果您尝试在其他Spring bean中注入该类型或名称的bean(例如使用 @Autowire ),则会获得该值。 所以这不是 @Bean 注解的好用法,除非您确实需要它。

另一方面, CommandLineRunner 是一个特殊的bean,允许您在应用程序上下文加载和启动后执行某些逻辑。 因此,在此使用restTemplate,调用url并打印返回的值是有意义的。

不久以前,注册Spring bean的唯一方法是使用xml。 因此,我们有像这样的xml文件和bean声明:

<bean id="myBean" class="org.company.MyClass">
  <property name="someField" value="1"/>
</bean>

@Configuration类相当于xml文件,@Bean方法相当于<bean> XML元素。

因此,在Bean方法中最好避免执行逻辑,只需创建对象并设置其属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接