CommandLineRunner和Beans(春季)

Pow*_*wer 2 spring

代码我的问题是什么:

   @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());
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

我是Spring的新手。据我了解,@ Bean注释负责将对象保存在IoC容器中,对吗?

如果是这样:首先是否收集了所有带有@Bean的方法,然后执行了这些方法?

在我的示例中,我添加了一个方法test()与run()相同,但是返回一个对象(Random())。结果是相同的,因此可以使用CommandLineRunner和Object。

是否有理由为什么要返回CommandLineRunner即使用run()之类的语法?

而且:到目前为止,我还没有看到将方法移到容器的优势。为什么不执行它呢?

谢谢!

Evg*_*rov 5

@Configurationclass(@SpringBootApplicationextends @Configuration)是春天豆的注册地。 @Bean用于声明一个Spring bean。带有注释的方法@Bean必须返回一个对象(bean)。缺省情况下,spring bean是单例的,因此一旦@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();
    }
Run Code Online (Sandbox Code Playgroud)

这将产生名称为“ test”的类型为Random的单例bean。因此,如果您尝试将@Autowire其他类型或名称的bean 注入(例如)到其他spring bean中,您将获得该值。因此@Bean,除非您确实需要注释,否则这不是注释的好用法。

CommandLineRunner另一方面是一个特殊的bean,通过它可以在加载和启动应用程序上下文之后执行一些逻辑。因此,在这里使用restTemplate,调用url并打印返回的值很有意义。

不久前,注册Spring bean的唯一方法是使用xml。因此,我们有一个xml文件和如下所示的bean声明:

<bean id="myBean" class="org.company.MyClass">
  <property name="someField" value="1"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

这些@Configuration类与xml文件等效,而@Bean方法与<bean>xml元素等效。

因此,最好避免在bean方法中执行逻辑,而要坚持创建对象和设置其属性。