<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
@RestController
public class HelloController {
// 注入对象
@Autowired
private Environment env;
@GetMapping("/hello")
public String hello() {
// 读取配置
String port = env.getProperty("server.port");
return port;
}
}
@RestController
public class HelloController {
// 注入配置
@Value("${server.port}")
private String port;
@GetMapping("/hello")
public String hello() {
return port;
}
}
@ConfigurationProperties(prefix = "net.biancheng")
@Component
public class MyConfig {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@RestController
public class HelloController {
@Autowired
private MyConfig myConfig;
@GetMapping("/hello")
public String hello() {
return myConfig.getName();
}
}
net.biancheng.name=zhangsan
application.properties 通用配置,不区分环境 application-dev.properties 开发环境 application-test.properties 测试环境 application-prod.properties 生产环境
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
{
"status": "UP"
}


management.endpoint.health.show-details=ALWAYS
{
"status": "UP",
"diskSpace": {
"status": "UP",
"total": 491270434816,
"free": 383870214144,
"threshold": 10485760
}
}
management.endpoints.web.exposure.include=configprops,beans
management.endpoints.web.exposure.include=*
@Component
public class UserHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.up().withDetail("status", true);
// builder.down().withDetail("status", false);
}
}
{
"status": "UP",
"details": {
"user": {
"status": "UP",
"details": {
"status": true
}
},
"diskSpace": {
"status": "UP",
"details": {
"total":
249795969024,
"free": 7575375872,
"threshold": 10485760
}
}
}
}
@Component
@Endpoint(id = "user")
public class UserEndpoint {
@ReadOperation
public List<Map<String, Object>> health() {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("userId", 1001);
map.put("userName", "zhangsan");
list.add(map);
return list;
}
}
[
{
"userName": "zhangsan",
"userId": 1001
}
]
{
"status": true,
"code": 200,
"message": null,
"data": [
{
"id": "101",
"name": "jack"
},
{
"id": "102",
"name": "jason"
}
]
}
{
"timestamp": 1492063521109,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/rest11/auth"
}
@ControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseData defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
logger.error("", e);
ResponseData r = new ResponseData();
r.setMessage(e.getMessage());
if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
r.setCode(404);
} else {
r.setCode(500);
}
r.setData(null);
r.setStatus(false);
return r;
}
}
# 出现错误时, 直接抛出异常 spring.mvc.throw-exception-if-no-handler-found=true # 不要为我们工程中的资源文件建立映射 spring.resources.add-mappings=false
{
"status": false, "code": 404,
"message": "No handler found for GET /rest11/auth", "data": null
}
public class ResponseData {
private Boolean status = true;
private int code = 200;
private String message;
private Object data;
// get set ...
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(() -> {
try {
// 业务逻辑
} catch (Exception e) {
e.printStackTrace();
} finally {
}
});
@Async
public void saveLog() {
System.err.println(Thread.currentThread().getName());
}
@Configuration
@ConfigurationProperties(prefix = "spring.task.pool")
public class TaskThreadPoolConfig {
// 核心线程数
private int corePoolSize = 5;
// 最大线程数
private int maxPoolSize = 50;
// 线程池维护线程所允许的空闲时间
private int keepAliveSeconds = 60;
// 队列长度
private int queueCapacity = 10000;
// 线程名称前缀
private String threadNamePrefix = "FSH-AsyncTask-";
// get set ...
}
@Configuration
public class AsyncTaskExecutePool implements AsyncConfigurer {
private Logger logger = LoggerFactory.getLogger(AsyncTaskExecutePool.class);
@Autowired
private TaskThreadPoolConfig config;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
executor.setMaxPoolSize(config.getMaxPoolSize());
executor.setQueueCapacity(config.getQueueCapacity());
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
executor.setThreadNamePrefix(config.getThreadNamePrefix());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initia lize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// 异步任务中异常处理
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
logger.error("==========================" + arg0.getMessage() + "=======================", arg0);
logger.error("exception method:" + arg1.getName());
}
};
}
}
spring.task.pool.maxPoolSize=100
server.port=${random.int[2000,8000]}
public class StartCommand {
private Logger logger = LoggerFactory.getLogger(StartCommand.class);
public StartCommand(String[] args) {
Boolean isServerPort = false;
String serverPort = "";
if (args != null) {
for (String arg : args) {
if (StringUtils.hasText(arg) && arg.startsWith("--server.port")) {
isServerPort = true;
serverPort = arg;
break;
}
}
}
// 没有指定端口, 则随机生成一个可用的端口
if (!isServerPort) {
int port = ServerPortUtils.getAvailablePort();
logger.info("current server.port=" + port);
System.setProperty("server.port", String.valueOf(port));
} else {
logger.info("current server.port=" + serverPort.split("=")[1]);
System.setProperty("server.port", serverPort.split("=")[1]);
}
}
}
server.port=${server.port}
public static int getAvailablePort() {
int max = 65535;
int min = 2000;
Random random = new Random();
int port = random.nextInt(max)%(max-min+1) + min;
boolean using = NetUtils.isLoclePortUsing(port);
if (using) {
return getAvailablePort();
} else {
return port;
}
}
public class FshHouseServiceApplication {
public static void main(String[] args) {
// 启动参数设置, 比如自动生成端口
new StartCommand(args);
SpringApplication.run(FshHouseServiceApplication.class, args);
}
}
<build> <plugins> <!-- 打包插件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> <mainClass>net.biancheng.spring_boot_example.App</mainClass> </configuration> </plugin> <!-- 编译插件, 指定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
需要框架源码请看我个人简介
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70006413/viewspace-2917486/ ,如需转载,请注明出处,否则将追究法律责任。