我正在开发一个基于Spring的应用程序,它注册了一个自定义范围“任务”。其想法是当启动一个新任务时,Spring应提供任务范围的对象。
任务在运行时实例化。它以Properties
对象的形式提供一些配置。我想将该对象注册到ApplicationContext
中,但在任务范围内,以便该范围内的所有bean都可以引用特定任务的配置。
下面是大致的代码思路:
public class MyTask extends SourceTask {
@Override
public void start(Map<String, String> props) {
context = ContextProvider.getApplicationContext();
// Initialize the scope
ConnectorTaskScope scope = context.getBean(ConnectorTaskScope.class);
scope.startNewTask();
// TODO register the props object in the context
// get an object which requires the properties and work with it
context.getBean(SomeScopedBean.class);
}
}
我不知道如何在适当的范围内注册一个Bean到ApplicationContext
中。
谢谢。
更新:
为了更好地解释问题,这里有更多的代码。 SomeScopedBean
应该使用它提供的配置做一些操作,看起来像这样:
public class SomeScopedBean {
@Autowire
public SomeScopedBean (Properties configuration) {
// do some work with the configuration
}
}
应用程序的想法是它应该有多个使用不同配置运行的MyTask
实例,每个任务都有自己的范围。在每个任务的范围内,应初始化1个使用该任务配置的SomeScopedBean
实例。
The idea of the application is that it should have multiple instances of MyTask
running with different configurations, and each task has its own scope. Within the scope of each task, there should be one instance of SomeScopedBean
initialized with the task's configuration.
public class MyApplication {
public static void main (String[] args) {
// ...
Properties config1 = loadConfiguration1();
Properties config2 = loadConfiguration2();
MyTask task1 = new MyTask();
MyTask task2 = new MyTask();
task1.start(config1);
task2.start(config2);
// ...
}
}
scope=prototype
吗?它会在注入时创建一个类的新实例。 - Downhillski