Why does Autowiring not function in a thread?

前端 未结 5 443
别那么骄傲
别那么骄傲 2021-02-06 07:13

I\'ve made a maven project in Spring 3.0, I\'ve made some DAO, services and controllers, in one of mine controller I call a service in which I start a thread, the problem is tha

相关标签:
5条回答
  • 2021-02-06 07:30

    For a bean to be autowired by Spring, the bean must be a Spring bean (i.e. be declared in the context.xml file or be annotated with a Spring annotation (@Service, @Component, etc.).

    And of course, it must be instantiated by Spring, and not by your code. If you instantiate a Spring bean yourself with new, Spring doesn't know about the bean, and doesn't inject anything into it.

    0 讨论(0)
  • 2021-02-06 07:36

    Had a similar issue had to Autowire in the service and pass to the method that implements runnable through the constructor.

    0 讨论(0)
  • 2021-02-06 07:42

    Spring just autowires beans of the context, no instances created by new. But why do you have declared uService in AddFriendInMyFriendListTask and not as a bean property of the outer (bean) class AddFriendInMyFriendListTaskExecutor, that should simply work:

    @Component
    public class AddFriendInMyFriendListTaskExecutor {
    
      private class AddFriendInMyFriendListTask implements Runnable {
    
        private final User a;
        private final User b;
    
        public AddFriendInMyFriendListTask(User aA, User bB) {
          a = aA;
          b = bB;
        }
    
        public void run() {
          AddFriendInMyFriendListTaskExecutor.this.uService.insertRightUserIntoLeftUserListOfFriends(a, b);
        }
      }
    
      @Autowired
      private IUserService uService;
    
      @Autowired
      private TaskExecutor taskExecutor;
    
      public void doIt(User a, User b) {
        taskExecutor.execute(new AddFriendInMyFriendListTask(a, b));
      }
    }
    

    (removed some unused getter/setter and made taskExecutor also a bean property)

    0 讨论(0)
  • 2021-02-06 07:43

    If you need to autowire a newly created instance (without container support) invoke

    ctx.getAutowireCapableBeanFactory().autowireBean(instance)

    where ctx is your ApplicationContext and instance the newly created instance.

    I asked a similar question here

    0 讨论(0)
  • 2021-02-06 07:46

    Another solution would be to inject the user IUserService in a spring managed component (service, component, etc.) and pass the injected value to the constructor of the class AddFriendInMyFriendListTask.

    Thus, the constructor becomes something like this

    public AddFriendInMyFriendListTask(User aA, User bB, IUserService userService) {
        a = aA;
        b = bB;
        this.userService = userService;
    }
    

    and remove the @Autowired from the AddFriendInMyFriendListTask class.

    0 讨论(0)
提交回复
热议问题