springboot成神之——springboot入門使用

<!-- TOC -->html

<!-- /TOC -->java

springboot建立webservice訪問mysql(使用maven)

安裝

使用maven,在你的pom.xml中添加以下配置
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.4.RELEASE</version>
</parent>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<optional>true</optional>
</dependency>

<plugin>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

maven package 測試是否安裝成功
mvn dependency:tree 查看你的安裝依賴

起步

src/main/java 下面添加一個類,假如以下代碼

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@SpringBootApplication                                                          // 聲明主程序類
@RestController                                                                 // 聲明咱們的類是一個web容器
@EnableAutoConfiguration                                                        // 自動配置spring
public class first {
	@RequestMapping("/")                                                        // 監聽("/")路由,返回字符串
	String home() {
		return "Hello World!";
	}
	public static void main(String[] args) {
		SpringApplication.run(first.class, args);                               // 開啓tomcat服務器,運行程序

	}
}

若是端口衝突,能夠配置tomcat的端口
在src/main/resources/
建立文件application.properties
加入 server.port=8888

# application.properties文件的格式
application.name=@project.name@
application.version=@project.version@

1. maven運行spring 
    運行 mvn spring-boot:run
2. 打包成可執行文件執行
    運行 mvn package 打包war文件
    運行 jar tvf FirstMaven-0.0.1-SNAPSHOT.war 查看war包裏面的內容
    運行 java -jar FirstMaven-0.0.1-SNAPSHOT.war 運行可執行文件
    訪問 http://localhost:8888/#/

spring經常使用命令

mvn dependency:tree                                                 查看依賴
mvn spring-boot:run                                                 運行程序
mvn package                                                         打包程序
jar tvf myproject-0.0.1-SNAPSHOT.jar                                查看jar包內部信息
java -jar myproject-0.0.1-SNAPSHOT.jar                              運行你的jar包

spring常見註釋

@RestController                                                     聲明是一個控制器和@Controller等效,用來處理網絡請求
@RequestMapping                                                     聲明請求的路徑
@Autowired                                                          自動注入,你能夠使用構造器注入來代替@Autowired,以下
    public class DatabaseAccountService implements AccountService {
        private final RiskAssessor riskAssessor;
        public DatabaseAccountService(RiskAssessor riskAssessor) {
            this.riskAssessor = riskAssessor;
        }
    }
    public class DatabaseAccountService implements AccountService {
        @Autowired 
        RiskAssessor riskAssessor;
    }
    上面二者等價
@SpringBootApplication                                              等價於開啓@EnableAutoConfiguration,@ComponentScan,@Configuration
@EnableAutoConfiguration                                            開啓spring默認依賴配置
@ComponentScan                                                      若是這個添加入口文件,那麼能夠掃描到@Component, @Service, @Repository, @Controller聲明的文件,而且自動註冊成bean
@Configuration                                                      容許配置其餘的bean和使用@Import導入其餘配置類
@Import                                                             導入其餘配置類@Import({ MyConfig.class, MyAnotherConfig.class })

springboot入門級使用

配置你的pom.xml文件

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>
  
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <java.version>1.8</java.version>
</properties>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>   
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
    
<plugin>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>
            -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
        </jvmArguments>
	</configuration>
</plugin>

配置文件

application.properties
    spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
    spring.datasource.username=root
    spring.datasource.password=123
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.max-idle=10
    spring.datasource.max-wait=1000
    spring.datasource.min-idle=5
    spring.datasource.initial-size=5
    server.port=8888
    server.session.timeout=10
    server.tomcat.uri-encoding=UTF-8

建立所需測試類

Greeting.java
    public class Greeting {

        private final long id;
        private final String content;

        public Greeting(long id, String content) {
            this.id = id;
            this.content = content;
        }

        public long getId() {
            return id;
        }

        public String getContent() {
            return content;
        }
    }

GreetingController.java

    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.atomic.AtomicLong;

    import javax.security.auth.message.callback.PrivateKeyCallback.Request;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;

    @RestController // 標記控制器返回一個域對象                                                                              
    public class GreetingController {
        @Autowired
        private JdbcTemplate jdbcTemplate;

        private static final String template = "Hello, %s!";
        private final AtomicLong counter = new AtomicLong();


        @CrossOrigin(origins = "http://localhost:8080") // 跨域設置
        @RequestMapping("/greeting") // 綁定路由,支持get,post,put,限定路由方式的寫法@RequestMapping(method=RequestMethod.GET,value="/greeting")
        public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
            return new Greeting(counter.incrementAndGet(), String.format(template, name));
        }
        
        @CrossOrigin(origins = "http://localhost:8080") 
        @RequestMapping(method=RequestMethod.GET,value="/mytest") 
        public List<Map<String, Object>>  mytest(@RequestParam(value="name", defaultValue="小紅") String name) { // @RequestBody Map<String,Object> params
            String sql = "select * from test WHERE name=?;";
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, name);
            return result;
        }
    }
first.java
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    public class first {
        public static void main(String[] args) {
            SpringApplication.run(first.class, args);
        }
    }

測試頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        // axios.get('http://localhost:8888/greeting').then(function (response) {
        //     console.log(response);
        // }).catch(function (error) {
        //     console.log(error);
        // }).then(function () {
        // });

        // axios.get('http://localhost:8888/greeting', {
        //     params: {
        //         name: 'User'
        //     }
        // }).then(function (response) {
        //     console.log(response);
        // }).catch(function (error) {
        //     console.log(error);
        // }).then(function () {
        // });

        axios.post('http://localhost:8888/greeting').then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        }).then(function () {
        });

        axios.post('http://localhost:8888/greeting', {
            name: 'User'
        }).then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        }).then(function () {
        });
    </script>
</head>
<body>
    
</body>
</html>

綁定路由的其餘方式

@GetMapping("/employees")
@GetMapping("/employees/{id}")

@PostMapping("/employees")

@PutMapping("/employees/{id}")
@DeleteMapping("/employees/{id}")
相關文章
相關標籤/搜索