2014-09-03 46 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_变量是不会被使用,我应该意识到尽可能多的默认范围

相关问题