2014-09-03 48 views
0

我按照使用Spring Framework的入門示例找到了here。我的問題與位於頁面上定義的應用程序類下的代碼具體交易:Spring方法需要創建新的匿名實例並且不允許使用現有的實例

package hello; 

import org.springframework.context.ApplicationContext; 
import org.springframework.context.annotation.*; 

@Configuration 
@ComponentScan 
public class Application { 

    @Bean 
    MessageService mockMessageService() { 
     return new MessageService() { 
      public String getMessage() { 
       return "Hello World!"; 
      } 
     }; 
    } 

    public static void main(String[] args) { 
     ApplicationContext context = 
      new AnnotationConfigApplicationContext(Application.class); 
     MessagePrinter printer = context.getBean(MessagePrinter.class); 
     printer.printMessage(); 
    } 
} 

具體來說,這部分在這裏:

@Bean 
    MessageService mockMessageService() { 
     return new MessageService() { 
      public String getMessage() { 
       return "Hello World!"; 
      } 
     }; 
    } 

此方法創建一個新的匿名MessageService對象上即時。在我的最後,我想創建一個實例,並且只需要使用mockMessageService方法返回單個實例(就像我多年來一直練習的那樣)。但是,當用以下方法替換該方法時,會遇到「服務爲空」輸出。

@Bean 
    MessageService mockMessageService() { 
     return messageService; 
    } 

    public static void main(final String[] args) { 
     final String message = "Hello World!"; 
     final MessageService messageService = new MockMessageService(message); 
     final Application app = new Application(); 
     app.messageService = messageService; 

     final ApplicationContext context = 
      new AnnotationConfigApplicationContext(Application.class); 
     final MessagePrinter printer = context.getBean(MessagePrinter.class); 
     if (printer == null) { 
      System.out.println("printer is null"); 
      return; 
     } 
     if (printer.getService() == null) { 
      System.out.println("service is null"); 
      return; 
     } 
     if (printer.getService().getMessage() == null) { 
      System.out.println("service message is null"); 
      return; 
     } 
     printer.printMessage(); 
    } 

    private MessageService messageService; 

所以,最後我的問題是,爲什麼我從使用類的一個單一實例禁止或者換句話說,爲什麼要創建一個新的實例它要求每次調用該方法?

回答

2

春天並沒有使用你自己創建的app實例。注意你通過彈出Application.class,它不知道你的app實例。如果您將​​實例成員更改爲static,則應該獲得您想要的內容。

+0

。我不敢相信我沒有看到。謝謝你的幫助。它現在(或常識)更有意義。 – Zymus 2014-09-03 08:18:03

0

如果你想創建一個單獨的實例,而不是將該對象的範圍標記爲單例,那麼你將得到該對象的單個實例。例如

@Bean 
@Scope("singleton") 

但因爲你沒有指定任何單是當我看到_app_變量是不會被使用,我應該意識到儘可能多的默認範圍

相關問題