如何启动spring 内嵌tomcatboot内嵌的tomcat工程

spring-boot(内嵌tomcat)上的薄封装,提供一个gui界面,用来配置端口和启动服务_springboot内嵌tomcat_词汇网
spring-boot(内嵌tomcat)上的薄封装,提供一个gui界面,用来配置端口和启动服务
责任编辑:词汇网 发表时间: 16:30:57
spring-boot上的薄封装,提供一个gui界面,用来配置端口和启动服务项目第一次启动时,会自动创建yml配置文件,log日志路径,static静态文件路径以及index.html文件你可以根据自己的业务,扩展UI界面和业务代码,实现一个免tomcat的服务端独立应用。用来构建轻量级的业务或者微服务再合适不过。源码地址:/aruis/spring-boot-gui-seed 标签: Spring 代码片段(5)[全屏查看所有代码] 1.[图片] 屏幕快照
上午8.59.37.png
2.[文件] Application.groovy~3KB 下载(0) package com.aruistar.serveruiimport org.yaml.snakeyaml.Yamlimport javax.swing.*/** * Created by liurui on 15/11/25. */class Application { public static void main(String[] args) { //自动创建static 静态文件 File webapp = new File(getProjectPath() + "/static/") if (!webapp.exists()) { webapp.mkdir(); File index = new File(getProjectPath() + "/static/index.html") index.write("""
Hello Spring-Boot-GUI-Seed""") } UICore ui = new UICore(); //自动创建yml配置文件 File ymlfile = new File(getProjectPath() + "/application.yml"); Yaml yaml = new Yaml(); if (!ymlfile.exists()) { ymlfile.write("""server: port: 7070isLog: truelogging: level: {org.springframework.web: ERROR}spring: resources: add-mappings: true"""); } def config = yaml.load(ymlfile.text); ui.config = if (config.isLog) { config.logging.path = getProjectPath() + "/log"; } else { config.logging.path = } //确定静态文件路径 config.spring.resources["static-locations"] = "file:" + getProjectPath() + "/static/"; ui.save = { -> ymlfile.write(yaml.dump(config)) } ymlfile.write(yaml.dump(config)); //向ui提供"端口"和"是否启动日志"信息 ui.setPort(config.server.port); ui.setIsLog(config.isLog); SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("软件应用配置"); frame.setSize(520, 360); frame.setContentPane(ui); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(true); } }); } //获取当前文件的运行路径 public static String getProjectPath() { java.net.URL url = Application.class.getProtectionDomain().getCodeSource().getLocation(); String filePath = try { filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8").replace("file:", "").replace("jar:", ""); } catch (Exception e) { e.printStackTrace(); } if (filePath.lastIndexOf("/") == filePath.length() - 1) { filePath = filePath.substring(0, filePath.length() - 1) } if (filePath.endsWith(".jar") || filePath.endsWith(".jar!")) { filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1); } java.io.File file = new java.io.File(filePath); filePath = file.getAbsolutePath(); return fileP }} 3.[文件] Server.groovy~1KB 下载(0) package com.aruistar.serveruiimport org.springframework.boot.autoconfigure.SpringBootApplicationimport org.springframework.boot.context.embedded.ServletRegistrationBeanimport org.springframework.context.annotation.Beanimport org.springframework.web.context.support.XmlWebApplicationContextimport org.springframework.web.servlet.DispatcherServlet/** * Created by liurui on 15/11/25. * 服务入口,可以在此配置Spring MVC的相关信息,具体可以参考spring boot的官方文档 http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/ */@SpringBootApplicationclass Server {//注释掉的内容是 flex项目相关配置,如果不需要flex支持,可以干掉// public DispatcherServlet flexDispatcherServlet() {// XmlWebApplicationContext appContext = new XmlWebApplicationContext();// appContext.setConfigLocation("classpath:/META-INF/flex-servlet.xml");// return new DispatcherServlet(appContext);// }//// @Bean// public ServletRegistrationBean dispatcherRegistrationFlex() {// ServletRegistrationBean registration = new ServletRegistrationBean(flexDispatcherServlet(), "/messagebroker/*");// registration.name = "flex"// registration.setLoadOnStartup(1)//// }} 4.[文件] UICore.groovy~10KB 下载(0) /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package com.aruistar.serveruiimport org.springframework.boot.SpringApplicationimport org.springframework.context.ApplicationContextimport javax.swing.*/** * * @author liurui */public class UICore extends javax.swing.JPanel { private ApplicationContext appC def config def save public UICore() { initComponents(); stopButton.enabled = false } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") //
private void initComponents() { startButton = new javax.swing.JButton(); stopButton = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); infoLabel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); portTextField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); saveButton = new javax.swing.JButton(); isLogCheckBox = new javax.swing.JCheckBox(); startButton.setText("启动服务"); startButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startButtonActionPerformed(evt); } }); stopButton.setText("关闭服务"); stopButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopButtonActionPerformed(evt); } }); jLabel1.setText("端口:"); portTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { portTextFieldActionPerformed(evt); } }); jLabel2.setText("是否启用日志:"); saveButton.setText("应用"); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.ponentPlacement.RELATED) .addComponent(isLogCheckBox)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(62, 62, 62) .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(infoLabel) .addPreferredGap(javax.ponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(saveButton) .addPreferredGap(javax.ponentPlacement.RELATED) .addComponent(startButton) .addPreferredGap(javax.ponentPlacement.RELATED) .addComponent(stopButton) .addGap(16, 16, 16)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(47, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jLabel2)) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(isLogCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(43, 43, 43) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.ponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(saveButton) .addComponent(startButton) .addComponent(stopButton) .addComponent(infoLabel)) .addGap(14, 14, 14)) ); }//
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:// System.setProperty("spring.resources.static-locations", Application.getProjectPath()+"/static/"); System.setProperty("spring.config.location", Application.getProjectPath() + "/application.yml") //String[] args = ["--spring.config.location=" + Application.getProjectPath() + "/application.yml"].toArray(); new Thread({ -> isLogCheckBox.enabled = startButton.enabled = stopButton.enabled = portTextField.enabled = saveButton.enabled = infoLabel.text = "启动中..." try { appContext = SpringApplication.run(Server.class) infoLabel.text = "已启动" isLogCheckBox.enabled = startButton.enabled = stopButton.enabled = portTextField.enabled = saveButton.enabled = stopButton.enabled = } catch (e) { e.printStackTrace() infoLabel.text = "启动失败" isLogCheckBox.enabled = startButton.enabled = stopButton.enabled = portTextField.enabled = saveButton.enabled = stopButton.enabled = } }).start(); } private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: if (appContext != null) { SpringApplication.exit(appContext); infoLabel.text = "" appContext = isLogCheckBox.enabled = startButton.enabled = stopButton.enabled = portTextField.enabled = saveButton.enabled = stopButton.enabled = } } private void portTextFieldActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: def port = portTextField.text.toString().trim(); if (port != "" && port.matches(/[\d]+/) && Integer.parseInt(port) <= 65536) { if (Tool.isPortAvailable(Integer.parseInt(port))) { config.server.port = } else { alert("端口无效或已被占用,请更换.") } } else { alert("端口由纯数字组成,建议选择范围.") } config.isLog = isLogCheckBox. if (config.isLog) { config.logging.path = Application.getProjectPath() + "/log"; } else { config.logging.path = } save() alert("保存成功.") } // Variables declaration - do not modify private javax.swing.JLabel infoL private javax.swing.JCheckBox isLogCheckB private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField portTextF private javax.swing.JButton saveB private javax.swing.JButton startB private javax.swing.JButton stopB // End of variables declaration def setPort(Object o) { portTextField.text = o.toString(); } public void alert(String text) { JOptionPane.showMessageDialog(this, text); } def setIsLog(boolean b) { isLogCheckBox.selected = }} 5.[文件] Tool.groovy~554B 下载(1) package com.aruistar.serverui/** * Created by liurui on 15/11/26. */class Tool { private static void bindPort(String host, int port) throws Exception { Socket s = new Socket(); s.bind(new InetSocketAddress(host, port)); s.close(); } public static boolean isPortAvailable(int port) { try {// bindPort("0.0.0.0", port); bindPort(InetAddress.getLocalHost().getHostAddress(), port); } catch (Exception e) { } }}
上一集:没有了 下一集:
相关文章:&&&&&&&&&&&&
最新添加资讯
24小时热门资讯
附近好友搜索今天看啥 热点:
spring boot 启动web,内嵌tomcat,springtomcat
1.pom.xml文件配置(酌情修改)
&project xmlns=&http://maven.apache.org/POM/4.0.0& xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xsi:schemaLocation=&http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&&
&modelVersion&4.0.0&/modelVersion&
&groupId&com.nnk.maven.test&/groupId&
&artifactId&test-sample&/artifactId&
&version&0.0.1-SNAPSHOT&/version&
&packaging&war&/packaging&
&properties&
&java.version&1.7&/java.version&
&start-class&com.nnk.maven.test.boot.Application&/start-class&
&/properties&
&!-- Inherit defaults from Spring Boot --&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-parent&/artifactId&
&version&1.0.1.RELEASE&/version&
&!-- Add typical dependencies for a web application --&
&dependencies&
&dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-web&/artifactId&
&/dependency&
&/dependencies&
&pluginManagement&
&artifactId&maven-compiler-plugin&/artifactId&
&configuration&
&source&1.7&/source&
&target&1.7&/target&
&/configuration&
&/plugins&
&/pluginManagement&
&repositories&
&repository&
&id&spring-snapshots&/id&
&url&http://repo.spring.io/snapshot&/url&
&snapshots&
&enabled&true&/enabled&
&/snapshots&
&/repository&
&repository&
&id&spring-milestones&/id&
&url&http://repo.spring.io/milestone&/url&
&/repository&
&/repositories&
&pluginRepositories&
&pluginRepository&
&id&spring-snapshots&/id&
&url&http://repo.spring.io/snapshot&/url&
&/pluginRepository&
&pluginRepository&
&id&spring-milestones&/id&
&url&http://repo.spring.io/milestone&/url&
&/pluginRepository&
&/pluginRepositories&
&/project&
2.实体类User
package com.nnk.maven.test.
public class User {
public Long getId() {
public void setId(Long id) {
public String getName() {
public void setName(String name) {
this.name =
public boolean equals(Object o) {
if (this == o)
if (o == null || getClass() != o.getClass())
User user = (User)
if (id != null ? !id.equals(user.id) : user.id != null)
public int hashCode() {
return id != null ? id.hashCode() : 0;
3.控制器Controller
package com.nnk.maven.test.
import org.springframework.web.bind.annotation.PathV
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
import com.nnk.maven.test.entity.U
@RestController
@RequestMapping(&/user&)
public class UserController {
@RequestMapping(&/{id}&)
public User view(@PathVariable(&id&) Long id) {
User user = new User();
user.setId(id);
user.setName(&zhang&);
4.spring-boot(tomcat启动)
package com.nnk.maven.test.
import java.util.HashS
import java.util.S
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.EnableAutoC
import org.springframework.ponentS
import org.springframework.context.annotation.C
@Configuration
@ComponentScan(&com.nnk&)
@EnableAutoConfiguration
// @SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setWebEnvironment(true);
app.setShowBanner(false);
Set&Object& set = new HashSet&Object&();
// set.add(&classpath:applicationContext.xml&);
app.setSources(set);
app.run(args);
注意:网上大部分@CompoentScan没有后面的value,如果不加必须保证所有的程序在一个包中,不然会出现404.
LZ 也是翻了好几个小时才发现是这个问题,所以写了一个比较完整的,避免来人再犯同样的错误!
相关搜索:
相关阅读:
相关频道:
&&&&&&&&&&&&&&&&
WEB编程教程最近更新Spring Boot如何集成duboo服务
分类:程序语言|标签:JAVA|日期:
Spring Boot是什么?
Spring Boot提供了一个强大的一键式Spring的集成开发环境,能够单独进行一个Spring应用的开发,其中:
(1)集中式配置(application.properties)+注解,大大简化了开发流程
(2)内嵌的Tomcat和Jetty容器,可直接打成jar包启动,无需提供Java war包以及繁琐的Web配置
(3)提供了Spring各个插件的基于Maven的pom模板配置,开箱即用,便利无比。
(4)可以在任何你想自动化配置的地方,实现可能
(5)提供更多的企业级开发特性,如何系统监控,健康诊断,权限控制
(6) 无冗余代码生成和XML强制配置
(7)提供支持强大的Restfult风格的编码,非常简洁
最近项目中,由于要写一个服务,所以就用到了比较方便的Spring Boot项目,之前也用过,和这次不一样的是这次的项目里面要使用阿里的duboo组件,作为服务化管理中心,原本的普通的spring项目集成dubbo是非常简单的,但由于用的Spring Boot,在网上搜了一下,还没有找到相关的资料的,所以就自己尝试了一下,发现并没有想象中的那么难,因为毕竟都是Spring自家的东西,没有理由不支持duboo。
当然这里这个例子,我是服务使用方,会调用别人提供的duboo服务,所以要通过xml声明duboo的服务发布方 , Spring Boot其实是支持xml的bean初始化的,虽然不推荐使用,但是它还是有这个功能的,Spring Boot更推荐的使用方式是注解+集中式的properties文件配置,但由于必须要使用Spring Boot,所以不得不这样干了, 先看下duboo的xml配置,该文件位于resource目录下:
另外在resource目录下,还需要加入dubbo.properties文件
dubbo.application.name=xxxx
dubbo.application.owner=xxxx
dubbo.application.logger=slf4j
dubbo.registry.address=zookeeper://:2181
dubbo.monitor.protocol=registry
dubbo.protocol.name=dubbo
dubbo.protocol.port=20887
dubbo.service.loadbalance=roundrobin
# dubbo \u8bbe\u8ba1\u\u\u53f0\u673a\ub\u8fd0\u884c\u4e00\u4e2ajvm\uff0c\u73b0\ua\u4e2a\u540c\u65f6\u4f7f\u7528\uff0c\u\u4fee\ud\u7f6e\u9879
dubbo.registry.file=/ROOT/tmp/dubbo_cus/www_xxxxx_cn.properties
然后需要在maven的pom文件中,加入duboo的依赖:
&!-- dubbo dependency --&
&dependency&
&groupId&com.alibaba&/groupId&
&artifactId&dubbo&/artifactId&
&version&2.4.1&&/version&
&exclusions&
&exclusion&
&artifactId&spring&/artifactId&
&groupId&org.springframework&/groupId&
&/exclusion&
&/exclusions&
&/dependency&
OK,接下来需要在Spring Boot的主启动类加上,第一步的定义的duboo的xml文件,截图:
package com.anytrust.index.
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.EnableAutoC
import org.springframework.ponentS
import org.springframework.context.annotation.C
import org.springframework.context.annotation.ImportR
@ComponentScan//组件扫描
@Configuration//配置控制
@EnableAutoConfiguration//启用自动配置
@ImportResource({&classpath:dubboContext.xml&}) //加入spring的bean的xml文件
public class ApplicationMain {
public static void main(String[] args) throws Exception {
//启动Spring Boot项目的唯一入口
SpringApplication.run(ApplicationMain.class, args);
一个测试的服务的类如下:
上面截图中,那个实例类,报错,不影响项目运行测试,所以可以忽略,最后,单元测试可以通过,后续会观察一下集成是否比较顺畅,因为Spring Boot是一个比较新的东西,虽然国外用的比较多,但国内用户还是比较少的,这样尝试,还是有点风险的,但测试一下也不错,如果可行,以后做项目也多了一种思路,还是挺好的。
最后欢迎大家扫码关注微信公众号:我是攻城师(woshigcs),我们一起学习,进步和交流!(woshigcs) 本公众号的内容是有关搜索和大数据技术和互联网等方面内容的分享,也是一个温馨的技术互动交流的小家园,有什么问题随时都可以留言,欢迎大家来访!
文章署名:qindongliang1922
文章地址:
优质IT资料分享网,由广大资源爱好者通过共享互助而共享各种学习资料,但本站无法保证所共享,资料的完整性和合理性
如果有资料对您的合法权益造成侵害,请立即联系我们处理}

我要回帖

更多关于 springboot内置tomcat 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信