带螺纹的弹簧Mvc

时间:2014-12-02 11:03:32

标签: spring 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()方法得到空指针异常时请帮助我。我是新手,有线程概念

1 个答案:

答案 0 :(得分:0)

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

要解决此问题,请在run()方法周围创建一个Runnable,并将其嵌入到方法中,如下所示:

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

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

        }}).start();
}

您需要将Thread实例绑定到AlertsToProfile中的字段,以避免泄漏并在您完成后停止该线程。