springboot(二)--入门案例(web应用、非web应用)

如题,上篇我们参照springboot官网,跑了下官方的helloworld,本篇我们尝试自己使用springboot创建项目。

你可以使用eclipse、myeclipse或 idea作为你的java IDE (或者如果你足够任性,也可以尝试下使用纯文本编辑器) 

一、springboot web应用程序 

创建一个 maven工程,起名为 helloSpringBoot,这是一个基于springboot的简单的web应用程序。

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.tingcream</groupId>
  <artifactId>helloSpringBoot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>helloSpringBoot</name>
  <url>http://maven.apache.org</url>
  
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
    </properties>
 
 <!-- 1 继承 spring boot默认的parent -->
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.15.RELEASE</version>
  </parent> 
 
  <!--2  如果是web项目,可以引入 starter-web  -->
  <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
   
   <!-- 3 其他依赖jar  -->
    <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <scope>test</scope>
    </dependency>
     
   </dependencies>
    
 
<build>
 
    <plugins>
          <!-- 4 spring-boot-maven-plugin插件 重要 -->
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            
    </plugins>
</build>
  
</project>         

SpringBootApp.java    ,作为springBoot程序入口类

package com.tingcream.helloSpringBoot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
  
@SpringBootApplication
//@SpringBootConfiguration  // the same as @Configuration
  
public class SpringBootApp extends SpringBootServletInitializer{
 
    //实现SpringBootServletInitializer接口 ,需实现此方法。  可以war包形式发布到tomcat中 
    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder builder) {
         return builder.sources(SpringBootApp.class);
    }
 
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }
 
}

HelloController.java

package com.tingcream.helloSpringBoot.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class HelloController {
     
    @ResponseBody
    @RequestMapping("/")
    public  String index(){
        return "hello SpringBoot 牛逼!!";
    }
}

如何运行springboot程序 :

1、找到SpringBootApp类,在IDE中直接右键run as   JavaApplicaton  运行

2、在项目根目录 mvn spring-boot:run  运行

3、在项目跟目录 mvn package  ,生成target目录,target中 生成 helloSpringBoot-0.0.1-SNAPSHOT.jar后,直接java -jar  helloSpringBoot-0.0.1-SNAPSHOT.jar 运行

 启动后,访问http://localhost:8080   

@SpringBootApplication 注解会开启自动配置,由于项目中引入了starter-web,springboot就会帮我们自动配置好springmvc的环境并启动项目包扫描,HelloController 标记了@Controller注解,成为了一个Controller控制器了,因此就可以直接被外部访问了。

二、springboot 非web应用程序(command line 或者GUI程序)

大多数开发者刚接触spring时,就是为了开发web程序,而且之后也是一直用spring开发web程序,脑海中似乎觉得spring就是为了开发web程序,其实不然。

实际上任何java应用都能冲从spring中受益,spring(springboot)不仅仅适用于web应用开发,也同样适用于非web程序(如java命令行、图形化程序)开发。

接下来,我们介绍下使用springboot开发一个命令行(控制台)程序--石头、剪刀、布的游戏。

创建一个mavn项目,起名为helloSpringBoot2,这是一个基于springboot的命令行程序。 

项目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.tingcream</groupId>
  <artifactId>helloSpringBoot2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <name>helloSpringBoot2</name>
  <url>http://maven.apache.org</url>
 
 <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
    </properties>
 
  <!-- 1 继承 spring boot默认的parent -->
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.15.RELEASE</version>
    </parent> 
   
  
  <dependencies>
  
         <!-- 核心(基本) starter   -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
         
   </dependencies>
 
<build>
    <plugins>
  
         <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        
    </plugins>
</build>
 
</project>

SpringBootApp.java 

package com.tingcream.helloSpringBoot2;
 
import java.util.Scanner;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.ComponentScan;
 
import com.tingcream.helloSpringBoot2.model.Computer;
import com.tingcream.helloSpringBoot2.model.Judger;
import com.tingcream.helloSpringBoot2.model.Player;
 
 
//@SpringBootApplication
@SpringBootConfiguration
//@EnableAutoConfiguration  //不使用自动配置特性
@ComponentScan
public class SpringBootApp  implements CommandLineRunner {
     
     
     public static void main(String[] args) throws Exception {
 
            SpringApplication.run(SpringBootApp.class, args);
 
      }
    
      
      @Autowired
      private  Player player ;//玩家
       
      @Autowired
      private Computer computer;//电脑
       
      @Autowired
      private Judger judger;//裁判
       
       
      /**
       * 石头、剪刀、布的游戏
       *
       */
    @Override
    public void run(String... args) throws Exception {
  
         System.out.println("请输入玩家名字 :");
        Scanner scanner=null;
         try {
            scanner =new Scanner(System.in);
            String welcomeMsg = player.getWelcomeMsg(scanner.nextLine().trim());
             
            while(true){
                System.out.println("========开始游戏========");
                System.out.println(welcomeMsg);//打印欢迎信息
                System.out.println("请玩家出拳(0石头、1剪刀、2布,按q键可退出游戏):");
                 
                String input =scanner.nextLine().trim();
                if(input.equalsIgnoreCase("q")){
                    System.out.println("游戏退出");
                    return  ;
                }
                 int inputA=-1;
                 try {
                     inputA = Integer.valueOf(input.trim());
                    if(inputA!=0 && inputA!=1 && inputA!=2){
                         System.out.println("输入非法,请重新输入,比赛重新开始");
                         continue;
                    }
                     
                 } catch (NumberFormatException e) {
                    System.out.println("输入非法,请重新输入,比赛重新开始!");
                    continue ;
                 }catch(Exception e ){
                     System.out.println("程序异常终止!");
                     return ;
                 }
                 
                 int inputB = computer.getNextGesture();//电脑出拳
                 System.out.println("你出的是:"+computer.getGestureName(inputA)+",电脑出的是:"+computer.getGestureName(inputB));
                  
                String result = judger.judge(inputA, inputB);//比赛结果
                System.out.println("比赛结果:"+result);//打印比赛结果
            }
             
        } finally{
            if(scanner!=null){
                scanner.close();
            }
        }
 
    }
}

Computer.java

package com.tingcream.helloSpringBoot2.model;
 
import java.util.Random;
 
import org.springframework.stereotype.Component;
  
 
/**
 * 电脑对象
 *
 */
@Component
public class Computer {
      
    private Random random =new Random();
     
     
     /**
      * 电脑  随机出拳
      * @return
      */
    public int  getNextGesture(){
       return   random.nextInt(3);//0  1  2
    }
     
    /**
     * 根据手势代号获取手势名称
     * @param code
     * @return
     */
    public  String  getGestureName(int  code){
        switch(code){
          case 0:
            return "石头";
          case 1:
              return "剪刀";
          case 2:
              return "布";
          default:
              return "未知";
        }
    }
 
}

Player.java

package com.tingcream.helloSpringBoot2.model;
 
 
import org.springframework.stereotype.Service;
 
/**
 * 玩家对象
 */
@Service
public class Player {
      
 
    public  String getWelcomeMsg(String name){
        return "欢迎您:"+name+",欢迎参加石头、剪刀、布的游戏!!!";
    }
     
}

Judger.java

package com.tingcream.helloSpringBoot2.model;
 
import org.springframework.stereotype.Component;
 
/**
 * 裁判对象 ,判定玩家vs电脑的胜负
 * @author jelly
 *
 */
@Component
public class Judger {
     
    /**
     * 判定胜负 
     *
     *    石头、剪刀、布  
     *    0   1   2
     *   
     *   游戏规则:  0胜1  ,1胜2 ,2胜利 0,数字相同则平局
     *
     * @param a  玩家出拳
     * @param b  电脑出拳
     * @return
     */
    public String judge(int a ,int b ){
        if(a==b){
            return "平局";
        }
        if(a==2 && b==0){
            return "恭喜,您获得了胜利";
        }
        if(a-b==-1){
            return "恭喜,您获得了胜利";
        }else {
            return "抱歉,您输了,请再接再厉";
        }
    }
     
 
}

mvn package , 

cd   target 

 java -jar helloSpringBoot2-0.0.1-SNAPSHOT.jar 运行

项目github地址:  https://github.com/jellyflu/Stone-scissors-cloth

 

 

 

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个使用Spring Boot搭建WebService的简单入门案例: 1.创建Spring Boot项目,在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> ``` 2.创建一个WebService类,在其中定义需要暴露的方法: ```java @WebService public interface HelloWorldService { @WebMethod String sayHello(String name); } ``` ```java @WebService(endpointInterface = "com.example.demo.webservice.HelloWorldService") public class HelloWorldServiceImpl implements HelloWorldService { @Override public String sayHello(String name) { return "Hello " + name + "!"; } } ``` 3.配置WebService的端点和实现类: ```java @Configuration public class WebServiceConfig { @Bean public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet() { MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(new AnnotationConfigApplicationContext(WebServiceConfig.class)); servlet.setTransformWsdlLocations(true); return new ServletRegistrationBean<>(servlet, "/ws/*"); } @Bean(name = "helloWorld") public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema xsdSchema) { DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition(); wsdl11Definition.setPortTypeName("HelloWorldPort"); wsdl11Definition.setLocationUri("/ws"); wsdl11Definition.setTargetNamespace("http://www.example.com/demo/webservice"); wsdl11Definition.setSchema(xsdSchema); return wsdl11Definition; } @Bean public XsdSchema xsdSchema() { return new SimpleXsdSchema(new ClassPathResource("hello.xsd")); } } ``` 4.创建XSD文件定义WebService的参数和返回值: ```xml <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.com/demo/webservice" xmlns:tns="http://www.example.com/demo/webservice" elementFormDefault="qualified"> <xs:element name="sayHelloRequest"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="sayHelloResponse"> <xs:complexType> <xs:sequence> <xs:element name="result" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ``` 5.启动应用程序,访问http://localhost:8080/ws/helloWorld.wsdl,将会看到生成的WSDL文件。 6.使用SOAPUI等工具测试webservice。 以上就是一个简单的Spring Boot Webservice入门案例

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值