繁体   English   中英

Spring方法需要创建新的匿名实例,并禁止使用现有实例

[英]Spring method requires creating new anonymous instance and disallows use of existing instance

我使用之后发现Spring框架的入门例子在这里 我的问题专门针对页面上定义的Application类下的代码:

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方法返回该实例(这是我多年的实践)。 但是,当用以下方法替换该方法时,输出“ service is null”。

    @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;

所以最终我的问题是,为什么我禁止使用该类的单个实例,或者换句话说,为什么每次调用该方法都需要创建一个新实例?

Spring没有使用您的app实例,而是创建了自己的实例。 请注意,您通过spring Application.class ,它不了解您的app实例。 如果将private MessageService messageService实例成员更改为static ,则应获得所需的内容。

如果要创建单个实例,而不将对象的范围标记为单例,则将获得该对象的单个实例。 例如

@Bean
@Scope("singleton")

但是由于您未指定任何内容,因此默认范围是单例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM