2014-12-02 77 views
0

大家好,我的线程类是显示,但空指针异常,请帮我解决Spring MVC的有螺纹

@Component 
public class AlertsToProfile extends Thread { 

    public final Map<Integer, List<String>> userMessages = Collections.synchronizedMap(new HashMap<Integer, List<String>>()); 

    @Autowired 
    ProfileDAO profileDAO; 

    private String categoryType; 

    private String dataMessage; 

    public String getCategoryType() { 
     return categoryType; 
    } 

    public void setCategoryType(String categoryType) { 
     this.categoryType = categoryType; 
    } 

    public String getDataMessage() { 
     return dataMessage; 
    } 

    public void setDataMessage(String dataMessage) { 
     this.dataMessage = dataMessage; 
    } 

    public void run() { 

       String category=getCategoryType(); 
       String data= getDataMessage(); 
       List<Profile> all = profileDAO.findAll(); 
       if (all != null) { 
        if (category == "All" || category.equalsIgnoreCase("All")) { 
         for (Profile profile : all) { 
          List<String> list = userMessages.get(profile.getId()); 
          if (list == null) { 
           ArrayList<String> strings = new ArrayList<String>(); 
           strings.add(data); 
           userMessages.put(profile.getId(), strings); 
          } else { 
           list.add(data); 
          } 
         } 
        } 
       } 
      } 

,我的服务方法如下

@Service 
public class NoteManager 
{ 


    @Autowired AlertsToProfile alertsToProfile; 

    public void addNote(String type, String message, String category) { 

     alertsToProfile.setCategoryType(category); 
     String data = type + "," + message; 
     alertsToProfile.setDataMessage(data); 

     alertsToProfile.start(); 
     System.out.println("addNotes is done"); 
    } 

当我调用start()方法得到空指针异常请帮助我。我是新来的弹簧线程概念

+0

请发布完整的堆栈跟踪 – 2014-12-02 11:15:14

回答

0

这很明显:你直接实例化你的线程,而不是让Spring创建AlertsToProfile并自动连线你的实例。

为了解决这个问题,创建一个在你的run()方法的Runnable并嵌入到这一点的方法,像这样:

public void startThread() { 
    new Thread(new Runnable() { 

     @Override 
     public void run() { 
      // your code in here 

     }}).start(); 
} 

你会想线程实例绑定到一个字段中AlertsToProfile为了以避免泄漏并在完成后停止线程。

+0

_you直接实例化您的线程_Autowired AlertsToProfile alertsToProfile' – zeroflagL 2014-12-02 13:06:02

+0

这也将工作。 – 2014-12-03 08:24:17

+0

谢谢Erik Schmiegelow其工作.. – 2014-12-05 11:26:28