• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解SpringBoot应用服务启动与安全终止

springboot 搞代码 4年前 (2022-01-05) 23次浏览 已收录 0个评论

这篇文章主要介绍了SpringBoot应用服务启动与安全终止,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

SpringBoot应用服务启动

参照官方示例工程可以快速搭建简单SpringBoot应用,官方连接如下:http://projects.spring.io/spring-boot/#quick-start
闲话少叙,上代码:

 package hello; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.*; @Controller @EnableAutoConfiguration public class SampleController { @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(SampleController.class, args); } } 

通过该main()函数作为入口,可以启动SpringBoot服务。虽然这里只有几行代码,当时已经是一个完整的web程序。

有几个注解需要特殊说明一下,我在开发的时候就在这几个注解上吃了不

来源gao!%daima.com搞$代*!码网

少亏。

@EnableAutoConfiguration:这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。

@ComponentScan:注解搜索beans,并结合@Autowired构造器注入。

@SpringBootApplication:等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan,不过该注解只搜索该包同级的包和下级的包!!!!!!

SpringBoot应用安全终止

由于SpringBoot集成了tomcat,所以当SpringBoot应用启动之后,不能像对普通的tomcat操作一下来操作SpringBoot,不过SpringBoot封装了启动,停止的方法。

SpringBoot,作为Spring框架对“约定优先于配置(Convention Over Configuration)”理念的最佳实践的产物,它能帮助我们很快捷的创建出独立运行、产品级别的基于Spring框架的应用,大部分Spring Boot应用只需要非常少的配置就可以快速运行起来,是一个与微服务(MicroServices)相当契合的微框架。

主要有两种方式:通过HTTP发送shutdown信号,或者通过service stop的方式,本文只介绍HTTP方式。

1.在pom.xml中引入actuator依赖

  org.springframework.bootspring-boot-starter-actuator

2.在application.properties文件开启shutdown endpoint,SpringBoot的endpoints.shutdown.enabled默认是关闭的。

 #启用shutdown endpoints.shutdown.enabled=true #禁用密码验证 endpoints.shutdown.sensitive=false

3.发送停止信号,使用curl向服务器发送post请求:

curl -X POST host:port/shutdown

 将会得到返回消息如下:

 {"message":"Shutting down, bye..."}

4.可以看出此方法非常方便,但是也很不安全,正式使用时,必须对该请求进行必要的安全设置,可以借助spring-boot-starter-security进行身份认证:
pom.xml添加security依赖

  org.springframework.bootspring-boot-starter-security

application.properties中变更配置

#开启shutdown的安全验证
endpoints.shutdown.sensitive=true
#验证用户名
security.user.name=admin
#验证密码
security.user.password=secret
#角色
management.security.role=SUPERUSER

 指定路径、IP、端口

#指定shutdown endpoint的路径
endpoints.shutdown.path=/custompath
#也可以统一指定所有endpoints的路径`management.context-path=/manage`
#指定管理端口和IP
management.port=8081
management.address=127.0.0.1

以上就是详解SpringBoot应用服务启动与安全终止的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解SpringBoot应用服务启动与安全终止

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址