解决非controller类引用service问题
项目中遇到需要采用socket通信机制,由于这个方法没有写在控制类里面,调用service类的时候老是报java.lang.NullPointerException错误
解决办法
1、首先将@Autowired注解注入Service或者Mapper接口
@Autowired
PaUserService pauserService;
2、设置静态变量
private static DomSocketUtils domSocketUtils;
3、初始化静态变量,注意要添加 @PostConstruct注解
@PostConstruct //用于在依赖关系注入完成之后需要执行的方法上,以执行任何初始化
public void init() {
domSocketUtils = this;
}
总的代码如下
@Component()
public class DomSocketUtils extends ServerSocket {
@Autowired
PaUserService pauserService;
private static final int SERVER_PORT = 8875; // 服务端端口
private static DomSocketUtils domSocketUtils;
private ServerSocket server;
// @PostConstruct
public DomSocketUtils() throws Exception {
// server=new ServerSocket(SERVER_PORT);
// load();
}
@PostConstruct //用于在依赖关系注入完成之后需要执行的方法上,以执行任何初始化
public void init() {
domSocketUtils = this;
}
@Async("taskExexutor")
public void load() throws Exception {
server=new ServerSocket(SERVER_PORT);
while (true) {
System.out.println("-----------等待连接-------- ");
Socket socket = server.accept();//接收连接服务端的客户端对象
System.out.println("ip" + socket.getInetAddress() + "已连接");
new Thread(new Transfer(socket),"thread1").start();// 每接收到一个Socket就建立一个新的线程来处理它
System.out.println(Thread.currentThread().getName());
}
}
class Transfer implements Runnable {
private Socket socket;
private DataInputStream dis;
private FileOutputStream fos;
public Transfer(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
dis = new DataInputStream(socket.getInputStream());
// 文件名和长度
String imageurl="";
String fileName = dis.readUTF(); //获取文件名
long fileLength = dis.readLong();
File directory = new File("E://"); //创建绝对路径
if(!directory.exists()) {
directory.mkdir();
}
File file = new File("E://");
fos = new FileOutputStream(basepath);//存入文件
// 开始接收文件
byte[] bytes = new byte[1024];
int length = 0;
while((length = dis.read(bytes, 0, bytes.length)) != -1) {
fos.write(bytes, 0, length);
fos.flush();
}
File file1 = new File(basepath);//读取文件
DicomInputStream dis = new DicomInputStream(file1);
Attributes fmi = dis.readFileMetaInformation();
Attributes attrs = dis.readDataset(-1, -1);
PaUser role = domSocketUtils.pauserService.getpaUserRole1(attrs.getString(Tag.PatientID));//验证是否存在该病人
System.out.println("======== 文件接收成功 [File Name:" + fileName + "] ");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fos != null)
fos.close();
if(dis != null)
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
注:socket文件接收的是dicom文件
在非controller层如何调用service层服务
通过init方法进行服务注入
@Slf4j
@Component
public class ServerIOT {
@Resource
private EasybandDateService easybandDateService;
@PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
public void init() {
serverIOT = this;
serverIOT.easybandDateService = this.easybandDateService;
// 初使化时将已静态化的easybandDateService实例化
}
}
调用方法形式如下
在前面添加当前类就可以了
boolean save = serverIOT.easybandDateService.save(easybandDate);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。