2017-04-14 83 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的方法,堅持創建對象並設置其屬性。