答:1.实现ApplicationRunner中的run方法。2.启动类加上@EnableAsync。3.然后通过异步的方式执行新线程。
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class OpenThreadTask implements ApplicationRunner {
@Autowired
private MyServerThread myServerThread;
@Override
@Async
public void run(ApplicationArguments args) {
myServerThread.run();
}
}
答: 使用@PostContrust。@Construct --> @AutoWired --> @PostContrust
@Component
public class BeanA {
@Autowired
private BeanB beanB;
public BeanA(){
System.out.println("这是 BeanA 的构造函数");
}
@PostConstruct
private void init() {
System.out.println("这是BeanA 的 init 方法");
beanB.testB(); // 调用测试函数
}
}
LogBean logModel = JSONObject.parseObject(JSONObject.toJSONString(valueMap), LogBean.class);
方式一
import com.xxx.common.AppBase;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoginCheckAspect {
@Around(value = "execution(* com.xxx.controller.*.*(..)) && " +
"!execution(* com.xxx.controller.SsoController.*(..)) "
)
public Object check(ProceedingJoinPoint pjp) throws Throwable {
AppBase.checkLogin();
return pjp.proceed();
}
}
方式二
--- Check.java
import com.xxx.common.AppBase;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoginCheckAspect {
@Around(value = "@annotation(com.xxx.backend.config.CheckLogin)")
public Object check(ProceedingJoinPoint pjp) throws Throwable {
AppBase.checkLogin();
return pjp.proceed();
}
}
--- CheckLogin.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 登录检查注解
*
*/
@Target(ElementType.METHOD)//注解使用范围
@Retention(RetentionPolicy.RUNTIME)//注解运行时机
public @interface CheckLogin {
}
--- method
@CheckLogin
@RequestMapping(value = "/getIt", method = RequestMethod.GET)
public ResultVO<?> getIt() throws AppException {
return ResultVO.success("it");
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
//api接口包扫描路径
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.xxx.controller";
public static final String VERSION = "1.0.0";
@Bean
public Docket createRestApi() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("Info-Token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build()
.globalOperationParameters(pars);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("数据服务") //设置文档的标题
.description("数据服务 API 接口文档") // 设置文档的描述
.version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
.build();
}
}
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
connector.setProperty("relaxedQueryChars", "|{}[]");
}
});
return factory;
}
/**
* url 参数转map
* @param url
* @return
*/
public static Map<String, String> getUrlMap(String url) {
String attrStr = HtmlUtils.htmlUnescape(url);
Map<String, String> map = new HashMap<>();
String[] text = attrStr.split("&"); // 转换为数组
for (String str : text) {
String[] keyText = str.split("="); // 转换key与value的数组
String key = "";
String value = "";
if (keyText.length < 1) {
continue;
} else if (keyText.length == 1) {
key = keyText[0]; // key
} else {
key = keyText[0]; // key
value = keyText[1]; // value
}
map.put(key, value);
}
return map;
}
public static void exportExcel(HttpServletResponse response, String fileName, List<List<String>> head, List<List<Object>> data, EasyExcelTitleHandler titleHandler) throws IOException,AppException {
// 写入内存输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
EasyExcel.write(baos).head(head).sheet().registerWriteHandler(titleHandler).doWrite(data);
// 非内网 安全检查
if(!AppBase.isClinetInternalIP()){
// copy一个byte数组
byte[] copyOfOutStreamBytes = baos.toByteArray();
try {
Check(fileName+".xlsx",copyOfOutStreamBytes);
} catch (AppException e) {
log.error("请求失败",e);
throw new AppException("安全检查出错,请稍候再试!");
}
}
//编码 防止中文乱码
try {
fileName = URLEncoder.encode(fileName,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
// 写入response的输出流
baos.writeTo(response.getOutputStream());
}