对于一个单例类按照平时的注解方式添加,启动时会报空指针异常,因为static类对象是创建对象后,内存中还没有注入Bean信息,且无法初始化Bean实例,这里的解决办法是利用@PostConstruct来对单例类中对象的注入。
@Component
public
class
DBManager {
private
static
DBManager instance =
new
DBManager();
@Autowired
public
UserServiceImpl userService;
private
DBManager() {
}
public
static
DBManager getInstance() {
return
instance;
}
@PostConstruct
public
void
init() {
instance =
this
;
instance.userService =
this
.userService;
}
}