java - 新实例 Spring 作用域

标签 java spring spring-boot instance autowired

我正在使用 Spring boot,我想知道是否有办法在每次调用特定方法时创建一个新实例。

我的意思是,我有一个专门用于创建 Autowiring 类的新实例的单例对象,并且我希望每次调用函数 init 时并且仅当我调用该对象的新实例时已创建。

@Component
public class PlatformFactoryManager {

    @Autowired
    private JiraFactory jiraFactory;

    /**
     * Obtain new factory instance of specified platform.
     */
    public IPlatformFactory getNewInstance(UserAccount userAccount, AuthenticationService authService, PlatformBean platform) {
        switch (platform.getPlatformName()) {
            case "Jira Restaurantes":
                jiraFactory.init(authService.getBy(userAccount.getUserId(), Platforms.JIRA_RESTAURANTES), platform);
                return jiraFactory;
            case "Jira Yapiko":
                jiraFactory.init(authService.getBy(userAccount.getUserId(), Platforms.JIRA_YAPIKO), platform);
                return jiraFactory;
            case "Jira FDJGS":
                jiraFactory.init(authService.getBy(userAccount.getUserId(), Platforms.JIRA_FDJGS), platform);
                return jiraFactory;
            default:
                return null;
        }
    }

}
@Component
public class JiraFactory implements IPlatformFactory {

    @Autowired
    private JiraBroker jiraBroker;

    private String platformName;
    private String url;

    public void init(UserAuthentication credentials, PlatformBean platform) {
        this.platform = platform;
        this.credentials = credentials;
        jiraBroker.init(platform.getUrl());
    }

...

}

每次调用 init 时,我都希望有一个 JiraFactory 的新实例,并且当我使用其他方法时,它是同一个对象。

有什么办法吗?

最佳答案

您还可以向组件添加@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)注释

关于java - 新实例 Spring 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60053725/

相关文章:

java - 按我的开火键时 SubKiller 游戏无法正常开火

java - 使用 Spring 和 Hibernate 的 REST Web 服务

Spring 休息国际化

java - 使用mvn测试版本号时Maven无法解析依赖关系

java - Spring Boot或Spring中用于异常和错误处理场景的工作流机制

java - 如何在postman中将多个字符串包装成单个字符串来调用spring boot Rest API Get请求

java - 如何按整数值对 HashMap 进行排序

JAVA基础编码。为什么100/1=110,300/3、400/4、500/5呢?

java - 使scrollRectToVisible与使用GroupLayout布局的面板一起使用

java - 从抽象类继承注释?