我正在使用 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/