Is Spring @autowired not meant for non-singleton containers?

后端 未结 4 1318
滥情空心
滥情空心 2020-12-14 19:21

I have a MyTask class which implements Runnable and there can be many such objects instantiated at any given moment. There are certain properties t

4条回答
  •  暖寄归人
    2020-12-14 20:04

    first, beans declared with @Component and picked up by spring component scan will become a spring-managed singleton by default.

    I have no idea how you use MyTask, but it is overkilled to use AspectJ in your situation, and it does not make much sense to declare MyTask as a spring-managed bean. another way of doing this will be:

    1. define MyTask as a plain java class and add a constructor to initialize the dependency blah

    2. autowire blah in where you use MyTask, and instantiate a MyTask object every time you want to execute a task as follow:

      //autowire the dependency of MyTask in another spring bean with default singleton scope
      @Autowired private SomeSpecialSpringConfiguredConnectionClass blah
      //create task and wire the blah yourself
      executor.submit(new MyTask(blah))
      

提交回复
热议问题