我按照使用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;
所以,最后我的问题是,为什么我从使用类的一个单一实例禁止或者换句话说,为什么要创建一个新的实例它要求每次调用该方法?
。我不敢相信我没有看到。谢谢你的帮助。它现在(或常识)更有意义。 – Zymus 2014-09-03 08:18:03