2017-04-14 173 views
0

码是什么,我的问题是关于:CommandLineRunner和豆类(春季)

@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()); 
     }; 
    } 
} 

我很新的春天。据我了解,@Bean注释是负责将对象保存在IoC容器中,请纠正?

如果是这样的话:首先收集@Bean的所有方法并执行然后执行

在我的例子,我添加的方法测试()是什么一样的run(),但返回的对象(随机())来代替。 结果与使用CommandLineRunner和Object时相同。

是否有一个原因,它应该返回CommandLineRunner即使用像奔跑的语法()?

此外:在这一点上我没有看到,到目前为止,移动的方法来一个集装箱的优势。为什么不直接执行它?

谢谢!

回答

2

@Configuration类(@SpringBootApplication延伸@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(); 
    } 

这将产生类型的随机名为 '试验' 第一个singleton 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的方法,坚持创建对象并设置其属性。