当前位置: 首页 > 知识库问答 >
问题:

自动装配时控制器为空

尉迟阳煦
2023-03-14

我有一个名为ReportController的控制器,它可以成功地访问存储库中的数据。我在另一个处理WebSocket消息的类中自动连接了该类,因为我还想在数据库之间发送WebSocket消息。然而,问题是,当我在SocketHandler类中自动连接控制器类并从那里调用方法时,它会给出一个空指针异常。我已经用@组件或@服务注释了控制器,但没有成功。我的课程如下

package com.labafrique.creporter;

import com.labafrique.creporter.property.FileStorageProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;

@EnableConfigurationProperties({
        FileStorageProperties.class
})
@SpringBootApplication

public class CreporterApplication {

    public static void main(String[] args) {
        SpringApplication.run(CreporterApplication.class, args);
    }

}

我的控制器类

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.labafrique.creporter.controller;

import com.google.gson.Gson;
import com.labafrique.creporter.model.ReportModel;
import com.labafrique.creporter.repository.ReportRepository;
import com.labafrique.creporter.service.FileStorageService;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author Javalove
 */

@Service
@RestController
@RequestMapping("/creporter/listener")
public class ReportController {

    @Autowired
    private ReportRepository caseRepo;

    @Autowired
    private FileStorageService fileStorageService;



    private static final Logger logger = LoggerFactory.getLogger(ReportController.class);


    @GetMapping(path="/getCases")
    @ResponseBody
    public String getCases(@RequestParam("t") String type, @RequestParam("x") String x)
    {
        return URLDecoder.decode(new Gson().toJson(caseRepo.findByCaseType(type, Integer.parseInt(x))));
    }

    @GetMapping(path="/getSent")
    @ResponseBody
    public String getSent(@RequestParam("sender") String sender, @RequestParam("email") String email, @RequestParam("phone") String phone, @RequestParam("type") String type)
    {
        try
        {
            email = URLEncoder.encode(email, "utf-8");
            sender = URLEncoder.encode(sender, "utf-8");
            phone = URLEncoder.encode(phone, "utf-8");
            type = URLEncoder.encode(type, "utf-8");
        }catch(Exception er){}
        return URLDecoder.decode(new Gson().toJson(caseRepo.getSent(sender, email, phone, type)));
    }


    @PostMapping(path="/add")
    @ResponseBody
    public String save(@RequestParam("code") String code, @RequestParam("category") String category, 
            @RequestParam("details") String details, 
            @RequestParam("audio") String audio, 
            @RequestParam("video") String video,
            @RequestParam("photo") String photo, 
            @RequestParam("address") String address, @RequestParam("rtype") String rtype, 
            @RequestParam("caseLocation") String caseLocation, 
            @RequestParam("userLocation") String userLocation,
            @RequestParam("photoFile") MultipartFile photoFile, 
            @RequestParam("videoFile") MultipartFile videoFile, 
            @RequestParam ("audioFile") MultipartFile audioFile,
            @RequestParam("email") String email,
            @RequestParam("phone") String phone,
            @RequestParam("sender") String sender,
            @RequestParam("thumb") String thumb)

    {
        String uploadingDir = System.getProperty("user.dir")+"/CReporterUploads/";
        System.out.println(uploadingDir);
        String result = "error";
        ReportModel model = new ReportModel();
        model.setAddress(address);
        model.setCaseLocation(caseLocation); 
        model.setCategory(category);
        model.setCode(code);
        model.setAudio(audio);
        model.setVideo(video);
        model.setPhoto(photo);
        model.setDetails(details);
        model.setRtype(rtype);
        model.setEmail(email);
        model.setSender(sender);
        model.setPhone(phone);
        model.setThumb(Integer.parseInt(thumb));
        model.setUserLocation(userLocation);
        if(audio.equals("true") )
        {
            doUpload(uploadingDir, audioFile, code);
        }
        if(video.equals("true") )
        {
            doUpload(uploadingDir, videoFile, code);
        }
        if(photo.equals("true") )
        {
            doUpload(uploadingDir, photoFile, code);
        }
        ReportModel md = caseRepo.save(model);
        /*
        if(attachment != null && attachment.length > 0)
        {
            logger.info("i'm in bro");
            uploadM(attachment, code);
        }
        */


        return new Gson().toJson(model);


    }

    @PostMapping(path = "/thmbUp")
    public void vote(@RequestParam("code") String code)
    {
        caseRepo.ThumbUp(code);
    }

    @GetMapping(path = "/welcome")
    public String getPage()
    {
        return "mapping";
    }




    public boolean doUpload(String uploadingDir, MultipartFile uploadedFile, String code)
    {
        System.out.println("about to upload photo");
        boolean done = false;
        File f = new File(uploadingDir +code + "/");
        if(!f.exists())
        {
            f.mkdirs();
        }
        try
        {
            File file = new File(uploadingDir + "/"+code + "/" +uploadedFile.getOriginalFilename());
            uploadedFile.transferTo(file);
        }
        catch(IOException er)
        {
            er.printStackTrace();
        }
        return done;
    }


    @GetMapping(path = "/test")
    public String test()
    {
        try{
        String uploadingDir1 = System.getProperty("user.dir") + "/creporter/";
        Path path = Paths.get(uploadingDir1);

        if (!Files.exists(path)) {

            Files.createDirectory(path);
            return("Directory created");
        } else {

            return("Directory already exists");
        }
        }catch(Exception er){return er.getMessage();}
    }




    @GetMapping("/getFile/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        // Load file as Resource
        String a[] = fileName.split("_");
        Resource resource = fileStorageService.loadFileAsResource(a[1], a[0]);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }




}

和我的套接字处理程序类

package com.labafrique.creporter.controller;

import com.labafrique.creporter.controller.ReportController;
import com.labafrique.creporter.repository.ReportRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class SocketHandler extends TextWebSocketHandler  {


        @Autowired
        ReportController report;




    List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            {
        //Map<String, String> value = new Gson().fromJson(message.getPayload(), Map.class);
        /*for(WebSocketSession webSocketSession : sessions) {
            webSocketSession.sendMessage(new TextMessage("Hello " + value.get("name") + " !"));
        }*/
            //session.sendMessage(new TextMessage("Hello " + value.get("name") + " !"));
                            try
                            {
                        System.out.println(message.getPayload());
                        session.sendMessage(new TextMessage("i received "+message));
                String t[] = message.getPayload().split("##");
                //try {session.sendMessage(new TextMessage(control.test())); }
                //catch(Exception ee){session.sendMessage(new TextMessage(ee.getMessage()));}
                session.sendMessage(new TextMessage("alldata##"+report.getCases("cor", "0")));
                if(message.getPayload().startsWith("AllData"))
                {
                    //System.out.println(control.("cor", "0"));
                    //session.sendMessage(new TextMessage("alldata##"+report.findByCaseType("cor", Integer.parseInt(t[1]))));
                }
                            }
                            catch(Exception er)
                            {
                                er.printStackTrace();
                            }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //the messages will be broadcasted to all users.
                session.sendMessage(new TextMessage("welcomeBro##xx"));
                //session.sendMessage(new TextMessage("alldata##"+report.findByCaseType("cor", 0)));
                //session.sendMessage(new TextMessage(control.test()));
        sessions.add(session);
    }

        public void sendLatest(String latest)
        {
            for(WebSocketSession webSocketSession : sessions) 
            {
                try
                {
                webSocketSession.sendMessage(new TextMessage("latest##"+latest));
                }catch(Exception er)
                {}
            }
        }

}

共有2个答案

尉迟德惠
2023-03-14

哇...经过将近一周的调试,我发现了问题......在我的Websocketconfig类中,我创建了一个新的SocketHandler实例,这就是导致问题的原因...所以我将我的配置类更改为

@Autowired
SocketHandler handler;

public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(handler, "/socket");
}

最初,我在register方法中有了新的SocketHandler()。我希望这对某人有所帮助。

常博裕
2023-03-14

你可以这样做。

@Service
public class ServiceBean {

    public String getCases(String type, String x)
    {
        return URLDecoder.decode(new Gson().toJson(caseRepo.findByCaseType(type, Integer.parseInt(x))));
    }
}

@RestController
@RequestMapping("/creporter/listener")
public class ReportController {

    @Autowired
    private ReportRepository caseRepo;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ServiceBean serviceBean;

    @GetMapping(path="/getCases")

    @ResponseBody
    public String getCases(@RequestParam("t") String type, @RequestParam("x") String x)
    {
        return serviceBean.getCase(type, x);
    }
}

@Component
public class SocketHandler extends TextWebSocketHandler  {

    @Autowired
    private ServiceBean serviceBean;

    // do here anything you want with methods of serviceBean
}
 类似资料:
  • 我有两个控制器< code>LoginViewController和< code>UserViewController 用户成功登录后,我需要将屏幕重定向到用户仪表板,并显示登录成功消息。 为此,可以使用两种方法 > < li> 由于我有一个在< code>UserViewController中加载用户仪表板的方法,所以我在< code>LoginViewController中自动连接了< cod

  • 这是我试图实现的:我有许多SpringRest无功控制器返回各种对象,如单声道,通量 我想将所有这些响应包装在响应实体中,因此总是返回这样的内容: 有什么建议吗?

  • 我正在我的一个项目中使用自动装配。在控制器中运行良好,但我需要在其他类中使用相同的自动装配对象,该类用作石英的任务类。自动装配在那里不起作用。 我尝试了下面列出的这段代码,但没有成功。在所有尝试中,它都为获取。 请提出解决方案,谢谢。

  • 我有控制器 我有一个控制器的组件 我还对我的控制器进行了测试。 当控制器调用。我得到一个。虽然我知道可以将添加到构造函数中,但我想知道是否有必要使用字段来实现这一点。如何确保字段注释在我的测试中有效?

  • Symfony文档指出,公共捆绑包应明确配置其服务,而不依赖于自动连接。因此,我使用下面的配置包来配置控制器服务。 安全参数是因为我正在使用身份验证Utils- 但是,这样的服务定义会产生弃用错误。用户弃用:自Symfony 4.2以来,弃用“blah\blah\SecurityController”容器的自动注入。将其配置为服务。在 /var/www/html/vendor/symfony/fr

  • 动画控制器视图 动画控制器视图允许你创建、查看和修改动画控制器资源。 动画控制器视图显示了一个新的空动画控制器资源 动画控制器视图主要有两部分:网格布局主体区域,左侧的分层和参数面板。 动画控制器视图的布局区域 深灰色网格部分是主体布局区域。你可以在这里创建、排列和连接 动画控制器 的状态(即动画剪辑)。 可以在网格上右键点击创建一个新的状态节点。使用鼠标中键拖动,或拖动时按住 Alt/Optio