关于工程中一些问题的解决

解决电磁加热工程中的问题。

问题:

项目启动时需要启动AmqpReceive的initAmqp方法,所以涉及到SpringBoot项目启动时自动执行指定方法,我最初是直接在启动类上调用,这样不太好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class HeaterApplication {

public static void main(String[] args) throws Exception {
SpringApplication.run(HeaterApplication.class, args);

// 1.
// AmqpReceive amqpReceive = new AmqpReceive();
//amqpReceive.initAmqp();

// 2.
//AmqpReceive amqpReceive = (AmqpReceive) StartupEvent.getBean(AmqpReceive.class);
//amqpReceive.initAmqp();
}
}

解决方案:

https://blog.csdn.net/rui15111/article/details/80996342

我这里选择了前者

1
2
3
4
5
6
7
8
9
@Component
public class AmqpReceive implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception { // 覆盖原来initAmqp方法
// TODO
}


}

问题:

此问题,解决了好久。AmqpReceive中自动注入之后运行为null,报空指针异常:

1
2
@Autowired
public static DeviceMapper deviceMapper; // 或者deviceServiceImpl

如上,在AmqpReceive类中进行了自动注入,在processMessage中调用了deviceMapper.updateDeviceShow(deviceShow);,结果运行报NPE,deviceShowprocessMessage方法内new,控制台打印不为空,deviceMapper为空。

解决方案:

针对自动注入的问题,试了很多方法,反射、初始化等等,都不行:

1
2
3
4
5
6
7
8
//  DeviceServiceImpl deviceServiceImpl = (DeviceServiceImpl) StartupEvent.getBean(DeviceServiceImpl.class);

// private static AmqpReceive amqpReceive;
// @PostConstruct
// public void init() {
// amqpReceive = this;
// amqpReceive.deviceServiceImpl = this.deviceServiceImpl;
// }

最终解决为和其他Controller一一对比,改成了如下:

1
2
@Autowired
private DeviceMapper deviceMapper;

可以了。

原因分析看这里。因为当类加载器加载静态变量时,Spring上下文尚未加载。所以类加载器不会在bean中正确注入静态类,并且会失败。

问题:

如上解决方案,自动注入mapper,有报错红线提示无法注入(我就说因为报错才把注入的mapper修改成static导致一直NPE),但其实不影响运行。

解决方案:

https://blog.csdn.net/qq_21853607/article/details/72802080

解决方法,在mapper加一个注解。@Component(value = “deviceMapper”)

:转载文章请注明出处,谢谢~