在使用普通类的时候,有时需要获取service,mapper等,直接使用自动注入@Autowired提示null异常
有两种解决方案
- 方案一:创建工具类SpringUtil
工具类
package com.websocket.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 普通类获取bean
*
* @author
*/
@Component
public class SpringUtil implements ApplicationContextAware {
private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
logger.info("ApplicationContext配置成功,applicationContext对象:" + SpringUtil.applicationContext);
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
普通类
package com.websocket.entity;
import com.websocket.service.TwoChatService;
import com.websocket.util.SpringUtil;
/**
* @author lenovo
*/
public class TestEntity {
TwoChatService twoChatService = SpringUtil.getBean(TwoChatService.class);
public Integer test(){
int count = twoChatService.count();
return count;
}
}
controller调用
@RestController
@RequestMapping("/chatRecord")
public class ChatRecordController {
@GetMapping("/test")
public Integer testController(){
TestEntity testEntity = new TestEntity();
return testEntity.test();
}
}
结果
- 方案二:初始化容器
普通类中直接初始化
package com.websocket.entity;
import com.websocket.service.TwoChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class TestEntity2 {
@Autowired
private static TestEntity2 testEntity2;
@Autowired
TwoChatService twoChatService;
@PostConstruct
public void init(){
testEntity2=this;
testEntity2.twoChatService=this.twoChatService;
}
public Integer test2(){
int count = testEntity2.twoChatService.count();
return count;
}
}
controller调用
@GetMapping("/test2")
public Integer testController2(){
TestEntity2 testEntity = new TestEntity2();
return testEntity.test2();
}
结果