1. 程式人生 > >一步一步學Spring Boot(一)

一步一步學Spring Boot(一)

開心一笑

老闆說:“年輕人,如果你想在這裡做事,有一件事情你必須要學會,那就是我們這個公司裡要求非常乾淨,你進來時在鞋墊上擦腳了嗎?”
年輕人:“哦,擦了,先生。”
老闆:“另外一件事是我們要求員工非常誠實,我們門口沒有鞋墊”。

提出問題

Spring Boot如何整合其他技術???

視訊教程

大家好,我錄製的視訊已經在CSDN學院釋出了,有興趣的同學可以購買觀看。相信大家一定會收穫到很多知識的。謝謝大家的支援……

解決問題

前言

Spring Boot這個技術現在非常流行,網上也有很多的資料,但是都不是很齊全。所以我花了點時間整理了一下,供大家學習。但是有一點要注意的是,這個資料不是很齊全,以後會進行更新,喜歡大家多多支援和鼓勵。以後有時間我會錄製成視訊,供大家學習。

程式碼在github上面有,可以去下載:* [email protected]:huangwenyi10/my-work.git*

快速搭建Spring Boot專案

如何快速搭建 Spring Boot 專案,可以參考我之前寫的一篇部落格。

Spring Boot 整合mySQL

用JdbcTemplate

1) 新增依賴

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId
>
</dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>

2)新增配置檔案配置資料庫和其他引數

在resource資料夾下新增application.properties配置檔案並輸入資料庫引數,如下:

spring.datasource.url=jdbc:mysql://127.0
.0.1:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 server.port=8011 server.session.timeout=10 server.tomcat.uri-encoding=UTF-8

3)新建測試類連線資料庫

package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void contextLoads() {
        List<Map<String,Object>> result = jdbcTemplate.queryForList("select * from ay_test");
        System.out.println("query result is" + result.size());
        System.out.println("success");
    }

}

Spring Boot整合MyBatis

MyBatis的整合總共有3中方式,這裡講解最簡單的一種方式。

第1步:引入mybatis的starter的包。 Spring Boot將封裝的一系列支援boot的應用的工程都叫做starter,我們這裡引入mybatis對boot的支援的starter。如果是同一個的pom,要註釋掉mybatis的依賴,starter會自動引入依賴包。

pom.xml

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>12345

第2步:配置properties。

spring.datasource.driver-class-name=com.mysql.jdbc.Driver //1
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=test
spring.datasource.password=123456
spring.datasource.max-active=10
spring.datasource.max-idle=5
spring.datasource.min-idle=0

mybatis.mapper-locations=classpath:/mybatis/*Mapper.xml //2
mybatis.type-aliases-package=com.hjf.boot.demo.boot_mybatis.domain

第3步:生成介面AppMessageMapper檔案

package com.example.mybatis.test;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Repository;
import java.util.List;

@Mapper
public interface AppMessageMapper {

    int deleteByPrimaryKey(String id);

    int insert(AppMessage record);

    int insertSelective(AppMessage record);

    AppMessage selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(AppMessage record);

    int updateByPrimaryKey(AppMessage record);

    List<AppMessage> selectAll();

    List<AppMessage> getMessById(String id);
}

第四步:生成實體類,服務層,服務層實現層,控制層

package com.example.mybatis.test;

import java.util.Date;
public class AppMessage {

    private String id;

    private String message;

    private Date senddate;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message == null ? null : message.trim();
    }

    public Date getSenddate() {
        return senddate;
    }

    public void setSenddate(Date senddate) {
        this.senddate = senddate;
    }
}
package com.example.mybatis.test;

import java.util.ArrayList;
import java.util.List;

public interface IAppMessageService {

    public List<AppMessage> getMessage();
    public List<AppMessage> getAllMessage();
    public int addMessage(AppMessage appMessage);
    public List<AppMessage> getMessageById(String id);
    public int delMessage(String id);
}
package com.example.mybatis.test;

import java.util.ArrayList;
import java.util.List;
import com.example.mybatis.test.AppMessage;
import com.example.mybatis.test.AppMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Component
public class AppMessageService implements IAppMessageService {

    @Autowired
    private AppMessageMapper appMessageMapper;

    @Override
    public List<AppMessage> getMessage(){
        List<AppMessage> list = new ArrayList<>();
        list.add(appMessageMapper.selectByPrimaryKey("xtt"));
        //list = mapper.selectAll();
        return list;
    }

    @Override
    public List<AppMessage> getAllMessage(){
        List<AppMessage> list = new ArrayList<>();
        list = appMessageMapper.selectAll();
        return list;
    }

    @Override
    public int addMessage(AppMessage appMessage) {
        return appMessageMapper.insert(appMessage);
    }

    @Override
    public List<AppMessage> getMessageById(String id) {
        return appMessageMapper.getMessById(id);
    }

    @Override
    public int delMessage(String id) {
        return appMessageMapper.deleteByPrimaryKey(id);
    }



}
package com.example.mybatis.test;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestBody;
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
@RequestMapping("/appmessage")
public class APPMessageController {


    private AppMessageService appMessageService;

    @RequestMapping("/getThree")
    public List<AppMessage> getThreeForMessage(){
        List<AppMessage> list = appMessageService.getMessage();
        return list;
    }

    @RequestMapping("/getAll")
    public List<AppMessage> getAllMessage(){
        List<AppMessage> list = appMessageService.getAllMessage();
        int num = list.size();
        if(null!=list && num>3){
            for (int i = 0; i < num-3; i++) {
                list.remove(0);
            }
        }
        return list;
    }

    @RequestMapping("/getByID")
    public List<AppMessage> getMessageById(@RequestParam("id") String id){
        List<AppMessage> list = appMessageService.getMessageById(id);
        int num = list.size();
        if(null!=list && num>5){
            for (int i = 0; i < num-5; i++) {
                list.remove(0);
            }
        }
        return list;
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public int addMessage(@RequestBody AppMessage appMessage){
        return appMessageService.addMessage(appMessage);
    }

    @RequestMapping(value="/delMessageById",method=RequestMethod.POST)
    public int delMessageById(@RequestParam("id") String id){
        return appMessageService.delMessage(id);
    }
}

第五步:建立資料庫表(mysql資料庫)

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `appuser_message`
-- ----------------------------
DROP TABLE IF EXISTS `appuser_message`;
CREATE TABLE `appuser_message` (
  `id` varchar(32) DEFAULT NULL,
  `message` varchar(500) DEFAULT NULL,
  `senddate` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of appuser_message
-- ----------------------------
INSERT INTO `appuser_message` VALUES ('1', '1', '2017-07-28');

檔案的目錄圖如下:

QQ截圖20170727111913

參考文章*

Spring Boot標籤總結

@SpringBootApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

說明:
1:用這個註解,就能實現自動掃描包和自動配置預設配置的功能,它包含了@ComponentScan和@EnableAutoConfiguration這兩個註解同時這個類自身也是一個配置類@Configuration,可以直接在這個類裡新增@Bean來注入java bean,第一章用的註解組合實現的和這個註解功能是一致的,這也是Spring Boot官方推薦的配置方式。

@configuration

用@Configuration註解該類,等價於XML中配置beans;用@Bean標註方法等價於XML中配置bean。

程式碼如下:

package SpringStudy;  

import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import SpringStudy.Model.Counter;  
import SpringStudy.Model.Piano;  

@Configuration  
public class SpringConfig {  
   @Bean  
   public Piano piano(){  
        return new Piano(); 
    }  

   @Bean(name = "counter")   
   public Counter counter(){  
        return  new Counter(12,"Shake it Off",piano());  
   }  
} 
@ImportResource

類級別註解,當我們必須使用一個xml的配置時,使用@ImportResource和@Configuration來標識這個檔案資源的類。

編寫ConfigClass注入配置檔案application-bean.xml;

在com.kfit.config包下編寫類ConfigClass,這個確保能被Spring Boot可以掃描到,不然一切都付之東流了,具體程式碼如下:

com.kfit.config].ConfigClass:

package com.kfit.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
 * classpath路徑:locations={"classpath:application-bean1.xml","classpath:application-bean2.xml"}
 * file路徑: locations = {"file:d:/test/application-bean1.xml"};
 */
@Configuration
@ImportResource(locations={"classpath:application-bean.xml"})
//@ImportResource(locations={"file:d:/test/application-bean1.xml"})
public class ConfigClass {

}

@RestController
@RequestMapping
@value

通過@value註解來讀取application.properties裡面的配置

face++ key
face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR  
face_api_secret =D9WUQGCYLvOCIdsbX35uTH****  
@Value("${face_api_key}")  
private String API_KEY;  
@Value("${face_api_secret}")  
private String API_SECRET;  

注意使用這個註解的時候 使用@Value的類如果被其他類作為物件引用,必須要使用注入的方式,而不能new。這個很重要,我就是被這個坑了。

Spring Boot 整合Quartz

第一步:新增依賴

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.3</version>
</dependency>

第二步:定義配置檔案 quartz.xml,名字自己取就可以了

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <aop:config proxy-target-class="true"/>
    <context:annotation-config/>
    <!-- 利用import引入定時器的檔案 -->
    <import resource="spring-quartz.xml"/>

</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- 使用MethodInvokingJobDetailFactoryBean,任務類可以不實現Job介面,通過targetMethod指定呼叫方法-->
    <bean id="taskJob" class="com.example.quartz.test.TestTask"/>
    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="group" value="job_work"/>
        <property name="name" value="job_work_name"/>
        <!--false表示等上一個任務執行完後再開啟新的任務-->
        <property name="concurrent" value="false"/>
        <property name="targetObject">
            <ref bean="taskJob"/>
        </property>
        <property name="targetMethod">
            <value>run</value>
        </property>
    </bean>
    <!--  排程觸發器 -->
    <bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="name" value="work_default_name"/>
        <property name="group" value="work_default"/>
        <property name="jobDetail">
            <ref bean="jobDetail" />
        </property>
        <property name="cronExpression">
            <value>0/10 * * * * ?</value>
        </property>
    </bean>
    <!-- 排程工廠 -->
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="myTrigger"/>
            </list>
        </property>
    </bean>
</beans>

第三步:建立定時器需要的類 TestTask

package com.example.quartz.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestTask {

    /** 日誌物件 */
    private static final Logger LOG = LoggerFactory.getLogger(TestTask.class);
    public void run() {
        if (LOG.isInfoEnabled()) {
            LOG.info("測試任務執行緒開始執行");
        }
        System.out.println("quarty run .....");
    }
}

第四步:讓spring boot掃描到配置檔案

主要是這個註解 @ImportResource(locations={“classpath:spring-mvc.xml”}),這樣spring boot就可以掃描到我們的配置檔案了

package com.example;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootApplication
@ImportResource(locations={"classpath:spring-mvc.xml"})
@EnableScheduling
public class DemoApplication{

   @Autowired
   private JmsTemplate jmsTemplate;

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

多個配置檔案的整合

例如,專案中有多個xml配置檔案:

  • Spring-Common.xml位於common資料夾下
  • Spring-Connection.xml位於connection資料夾下
  • Spring-ModuleA.xml位於moduleA資料夾下

    你可以在程式碼中載入以上3個xml配置檔案

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml","Spring-Connection.xml","Spring-ModuleA.xml"});

但是這種方法不易組織並且不好維護,最好的方法是在一個單獨的xml的配置檔案中組織其他所有的xml配置檔案。例如,可以建立一個Spring-All-Module.xml檔案,然後將其他的xml配置檔案匯入到Spring-All-Module.xml中,就像下邊這樣,

Spring-All-Module.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <import resource="common/Spring-Common.xml"/>
    <import resource="connection/Spring-Connection.xml"/>
    <import resource="moduleA/Spring-ModuleA.xml"/>
</beans>

現在,你可以在程式碼中載入一個單獨的xml配置檔案,如下:

ApplicationContext context =    new ClassPathXmlApplicationContext(Spring-All-Module.xml);

Spring Boot整合Redis

第一步:新增依賴

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis -->
<!-- 注意包都要拿最新的版本 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>

第二步:配置properties

#redis
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0
第三步:測試類
package com.example.redis.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Ay
 * @date   2017/1/24.
 */
@RestController
@EnableAutoConfiguration
public class HelloRedisTestController {

    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/redis")
    public String index(){
        // 儲存字串
        stringRedisTemplate.opsForValue().set("aaa", "111");
        String string = stringRedisTemplate.opsForValue().get("aaa");
        System.out.println(string);
        return "Hello Ay...";
    }
}
參考文章

Spring Boot 整合 ActiveMQ

安裝

【1】

第一步:新增依賴

<!-- ActiveMQ dependency start-->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jms</artifactId>
</dependency>
<dependency>
   <groupId>org.apache.activemq</groupId>
   <artifactId>activemq-client</artifactId>
</dependency>
<!-- ActiveMQ dependency end-->

第二步:定義配置檔案

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <aop:config proxy-target-class="true"/>
    <context:annotation-config/>

    <import resource="spring-quartz.xml"/>


    <!-- 配置JMS連線工廠 -->
    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="failover:(tcp://localhost:61616)" />
    </bean>

    <!-- 定義訊息佇列(Queue) -->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <!-- 設定訊息佇列的名字 -->
        <constructor-arg>
            <value>myQueue</value>
        </constructor-arg>
    </bean>

    <!-- 配置JMS模板(Queue),Spring提供的JMS工具類,它傳送、接收訊息。 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="queueDestination" />
        <property name="receiveTimeout" value="10000" />
    </bean>

    <!--queue訊息生產者 -->
    <bean id="producerService" class="com.example.mq.test.ProducerServiceImpl">
        <property name="jmsTemplate" ref="jmsTemplate"></property>
    </bean>

    <!--queue訊息消費者 -->
    <bean id="consumerService" class="com.example.mq.test.ConsumerServiceImpl">
        <property name="jmsTemplate" ref="jmsTemplate"></property>
    </bean>

</beans>

第三步:定義消費者和生產者類

生產者類介面ProducerService

package com.example.mq.test;

import org.springframework.stereotype.Component;

import javax.jms.Destination;

public interface ProducerService {

    /**
     * 發訊息,向預設的 destination
     * @param msg String 訊息內容
     */
    public void sendMessage(String msg);

    /**
     * 發訊息,向指定的 destination
     * @param destination 目的地
     * @param msg String 訊息內容
     */
    public void sendMessage(Destination destination, String msg);

    /**
     * 發訊息,向指定的 destination
     * @param destination 目的地
     * @param msg String 訊息內容
     */

    /**
     * 向指定的destination傳送訊息,消費者接受訊息後,把回覆的訊息寫到response佇列
     * @param destination 目的地
     * @param msg String 訊息內容
     * @param response 回覆訊息的佇列
     */
    public void sendMessage(Destination destination, String msg, Destination response);
}

生產者類實現

package com.example.mq.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

public class ProducerServiceImpl implements ProducerService{

    @Autowired
    private JmsTemplate jmsTemplate;

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }