背景
做了一个springboot集成mina时,解码失败后,会将ip信息添加到数据库中。但利用@Autowired注入service层后,编译正常,运行到调用的地方,报空指针异常,跟踪异常位置,发现service为空。
1. 解决方案一
1.1 代码
@Component
public class CustomProtocolDecoder extends CumulativeProtocolDecoder {
@Autowired
private MachineIpBlacklistService machineIpBlacklistService;
private static CustomProtocolDecoder customProtocolDecoder;
// 通过@PostConstruct实现初始化bean之前进行的操作
@PostConstruct
public void init() {
customProtocolDecoder = this;
// 测试发现不写此段代码也可以使用,但不知道为什么,希望大神可以解惑。
customProtocolDecoder.machineIpBlacklistService = this.machineIpBlacklistService;
}
// 测试调用
customProtocolDecoder.machineIpBlacklistService.<你的service层方法>;
}
1.2 说明
- 将需要调用Spring的Service层的类通过@Component注解为组件加载;
- 同样通过@Autowired获取Service层的Bean对象;
- 为类声明一个静态变量,方便下一步存储bean对象。
重点:
通过注解@PostConstruct,在初始化的时候初始化静态对象和它的成员变量service,原理是拿到service层bean对象,静态存储下来,防止被释放。
2. 解决方案二
2.1 创建spring工具类代码
package net.froeasy.wpc.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
/**
* 下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
System.out.println("获取spring管理的bean成功");
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
public static Object getBean(String name, Class<?> requiredType)
throws BeansException {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}
2.2 使用
MachineIpBlacklistService machineIpBlacklistService = (MachineIpBlacklistService) SpringContextUtil.getBean("machineIpBlacklistServiceImpl");·