[출처] http://stackoverflow.com/questions/7405232/why-does-autowiring-not-function-in-a-thread


Why does Autowiring not function in a thread?


 

 

 

 

 

 

 

 
up vote

2

down vote

favorite

1
 


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 that in the thread I declare a "service variable" that should be initialized with Autowired annotiation, but it doesn't work and the variable isn't initilized and has the value null.

this is the thread class
package com.project.tasks;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import com.project.entities.user.User;
import com.project.services.IUserService;

@Component
public class AddFriendInMyFriendListTaskExecutor {
private class AddFriendInMyFriendListTask implements Runnable {


     // HERE IS THE PROBLEM
    @Autowired
    private IUserService uService;

    private User a;
    private User b;

    public AddFriendInMyFriendListTask() {
        ;
    }

    public AddFriendInMyFriendListTask(User aA, User bB) {
        a = aA;
        b = bB;
    }

    public User getA() {
        return a;
    }
    public void setA(User a) {
        this.a = a;
    }
    public User getB() {
        return b;
    }
    public void setB(User b) {
        this.b = b;
    }


    public void run() {
                    // FROM HERE IT PRINTS THE VALUE OF uService THAT IS NULL
        System.out.println("uService:" + uService);
        uService.insertRightUserIntoLeftUserListOfFriends(a, b);
    }
}

private TaskExecutor taskExecutor;

  public AddFriendInMyFriendListTaskExecutor(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
  }

  public void doIt(User a, User b) {
      taskExecutor.execute(new AddFriendInMyFriendListTask(a, b));
  }
}

this is the piece of code that calls the thread
    User a = uDao.getUser(hrA.getMyIdApp());
    User b = uDao.getUser(hrA.getOtherIdApp());
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    AddFriendInMyFriendListTaskExecutor tmp = new AddFriendInMyFriendListTaskExecutor(taskExecutor);
    tmp.doIt(a, b);

I'd like to highlight that in all the other tests in which I don't call any threads, the Autowired of a UserService instance functions correctly! The method I call: insertRightUserIntoLeftUserListOfFriends(User a, User b), works correctly.

java multithreading spring task autowired


share|improve this question
 

edited Sep 13 '11 at 21:04

 

 
stacker
31.7k549106
 

asked Sep 13 '11 at 16:25

 

 
user942458
1112
 
 
 

 
add comment 

 


4 Answers

 

active

oldest

votes
 


 
up vote

6

down vote
 

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.


share|improve this answer
 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

answered Sep 13 '11 at 16:36

 

 
JB Nizet
211k12111250
 
 
 


   
 
No. You instantiate AddFriendInMyFriendListTaskExecutor using new AddFriendInMyFriendListTaskExecutor(), the inner class AddFriendInMyFriendListTask (which should be static) is not annotated, and you instanciate it using new as well. ?  JB Nizet Sep 13 '11 at 16:45 
 

   
 
Excuse me probably I don't understand your answer, or I'm not able to explain my problem, the creation of the AddFriendInMyFriendListTaskExecutor instance dosen't give me any problem, infact after the code :"AddFriendInMyFriendListTaskExecutor tmp = new AddFriendInMyFriendListTaskExecutor(taskExecutor);" tmp is not null, the problem is when I use uService into the class AddFriendInMyFriendListTask, there's no problem with the calss and the initilization of AddFriendInMyFriendListTask's instances ?  user942458 Sep 13 '11 at 17:09
 

1    
 
Spring must instantiate the spring beans. Not you. You can not use the new operator to instantiate spring beans. They must either be injected in the current bean by Spring, or you must get them from the bean factory. ?  JB Nizet Sep 13 '11 at 17:45
 
add comment 
 

 

 

 

 

 

 


 
up vote

1

down vote
 

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)


share|improve this answer
 

answered Sep 13 '11 at 21:36

 

 
Arne Burmeister
7,59311943
 
 
 

 
add comment 
 


 
up vote

0

down vote
 

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


share|improve this answer
 

answered Sep 13 '11 at 20:56

 

 
stacker
31.7k549106
 
 
 

 
add comment 
 


 
up vote

0

down vote
 

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.


share|improve this answer
 

answered Sep 13 '11 at 21:10

 

 
aseychell
994721
 
 
 

 
add comment 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
30 Java XML Parse, Java XML 파싱 샘플 졸리운_곰 2015.03.03 814
29 Java Inner class 자바 중첩(내부)클래스 졸리운_곰 2015.03.03 886
28 IzPack으로 GUI 설치 프로그램 만들기 file 졸리운_곰 2015.02.15 638
27 [Java],[AWT],[Layout],[AWT Layout], file 졸리운_곰 2015.02.13 368
26 [Java],[AWT],[SWING], Java GUI file 졸리운_곰 2015.02.13 922
25 [Java][AWT 개요] file 졸리운_곰 2015.02.13 463
24 javac 로 컴파일 시 유니코드(utf-8) 한글 소스 코드 컴파일 문제 졸리운_곰 2015.02.02 1133
23 [스프링] 스프링 Java 어노테이션 file 졸리운_곰 2014.06.11 960
22 [스프링] 스프링 MVC 졸리운_곰 2014.06.11 532
21 [스프링] 어노테이션 졸리운_곰 2014.06.11 1032
20 인코딩 - 8859_1의 비밀(?) file 졸리운_곰 2014.05.06 581
19 [JNI] 안드로이드 JNI 환경에서 C++과 Java 간의 한글 데이터 전송 문제 졸리운_곰 2014.05.06 597
18 자바 암호화 복호화 file 졸리운_곰 2014.04.08 2495
17 파일 존재 여부 판단, 디렉토리 있는지 확인 함수; File Directory Exist 졸리운_곰 2014.03.03 1215
16 NetStat call and get result text in Java 졸리운_곰 2014.02.25 903
» [Spring] @Autowired 와 Java Spring 졸리운_곰 2014.01.29 1332
14 Java Static 변수 졸리운_곰 2014.01.28 1102
13 Properties 클래스 사용하기. 졸리운_곰 2014.01.28 1024
12 Java => Thread 졸리운_곰 2014.01.28 834
11 [Spring] 내가 Spring을 사랑하는 다섯 가지 이유 file 가을의 곰을... 2013.12.22 970
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED