Feture简介
常用的方法介绍
易出错的地方
@Service
public class XxxService{
public void methodA(){
...
XxxService xxxServiceProxy = SpringUtil.getBean(XxxService.class);
xxxServiceProxy.methodB();
...
}
@Async
public void methodB() {
...
}
}
package com.zhiliyuchi.web.rest.controller;
import com.zhiliyuchi.domain.fishpond.ManagerEntity;
import com.zhiliyuchi.repository.fishpond.ManagerRepository;
import com.zhiliyuchi.web.rest.util.Result;
import com.zhiliyuchi.web.rest.util.SpringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @创建人:Young
* @时 间: 2019/3/13
* @描 述: Manager类Controller接口类
*/
@RestController
@RequestMapping("manager")
public class ManagerController {
private final Logger logger = LoggerFactory.getLogger(ManagerController.class);
@Autowired
private ManagerRepository managerRepository;
// @Autowired
// private AsyncController asyncController;
/**
* @描述 查询所有的数据的异常测试类
* @参数 []
* @返回值 com.zhiliyuchi.web.rest.util.Result
* @创建人 Young
* @创建时间 2019/3/13 14:05
**/
@GetMapping("all")
public Result getAll(){
ManagerController bean = SpringUtils.getBean(ManagerController.class);
logger.debug("查询所有的manager");
List<ManagerEntity> all = managerRepository.findAll();
bean.test();
bean.test();
return Result.error("数据请求服务未启用","type","subtype");
}
@Async
public void test(){
try {
logger.debug("=======开始执行异步处理类========");
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
}
}
StringUtils的工具类,手动获取bean方法:
package com.zhiliyuchi.web.rest.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @创建人:Young
* @时 间: 2019/3/13
* @描 述: 手动获取spring的bean
*/
@Component("springContextUtil")
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanId) {
return (T) applicationContext.getBean(beanId);
}
public static <T> T getBean(Class<T> requiredType) {
return (T) applicationContext.getBean(requiredType);
}
/**
* Spring容器启动后,会把 applicationContext 给自动注入进来,然后我们把 applicationContext
* 赋值到静态变量中,方便后续拿到容器对象
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
}