2019-7-22 Springboot搭建集成

一、概念:

1、认识:

           SpringBoot 它Spring里面提供一个框架,或者一些maven的集合,(提供很多starter)

     我们通过它,可以快速的构建项目 编译和部署,监控;

2、特点:

      ①、快速构建项目

      ②、对主流开发框架的无配置集成

      ③、项目可独立运行,无须外部依赖Servlet容器(Spring Boot默认自带了一个Tomcat)

      ④、提供运行时的应用监控

      ⑤、极大地提高了开发、部署效率

二、入门程序:

1、创建maven父项目,导入依赖

      spring boot 父节点依赖,引入这个之后相关的引入就不需要添加version配置,spring boot会自动选择最合适的版本进行添加。

    <parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.5.RELEASE</version>
    </parent>

2、创建子模块项目,导入web依赖

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

3、创建controller

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello word";
    }
}

4、创建springboot启动类(注意注解+main方法)

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

5、测试:http://localhost:8080/hello

6、引入热部署依赖(原理是使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个   ClassLoader加载会更改的类(自己写的),称为  restart ClassLoader)

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

热部署:在idea要手动编译(ctrl+f9)

三、集成SpringBoot-Test:

1、导入Test依赖:

  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
  </dependency>

2、创建启动类与测试类

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

 

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplicationConfig.class)//加载哪个Spring配置文件
public class TestApplicationConfigTest
{
    @Test
    public void beanTest()throws Exception{
        System.out.println("springboot測試顶顶顶顶");
    }
}

四、集成JSP

1、创建maven-webapp项目模块,导入依赖:

        <!-- servlet 依赖. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- tomcat 的支持. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

2、在webapp/WEB-INF/文件夹下创建:views/hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hello-jsp</title>
</head>
<body>
    hello ${msg}
</body>
</html>

3、在resources配置文件配置相关信息:application.properties

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp
# 自定义属性,可以在Controller中读取
application.hello=Hello Angel From application

4、创建controller

@Controller
public class JspController {

    @RequestMapping("/jsp")
    public String jspTest(Model model){
        model.addAttribute("msg","1234" );
        return "hello";
    }
}

5、创建启动类

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

注意:在使用模块开发的时候,启动tomcat 访问jsp 需要配置:working directory :%MODULE_WORKING_DIR%

五、集成freemarker:

1、导入依赖:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、于resources文件夹下创建templates文件夹创建freemarker模板(注意:templates 与模板后缀:.frl)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>freemarker</title>
</head>
<body>
    hello  ${msg}
</body>
</html>

 

3、配置文件application.properties:

# FreeeMarker 模板引擎配置
#       设定ftl文件路径
spring.freemarker.tempalte-loader-path=classpath:/templates
#        关闭缓存,及时刷新,上线生产环境需要修改为true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl

4、创建controller与启动类

@Controller
public class FreemakerController {

    @RequestMapping("/freemarker")
    public String freemakerTest(Model model){

        model.addAttribute("msg", "123456");
        return "freemarker";
    }
}
@SpringBootApplication
public class FreemakerApplicationConfig
{
    public static void main( String[] args )
    {
        SpringApplication.run(FreemakerApplicationConfig.class);
    }
}

六、集成json(与之前的操作一样)

1、导入依赖

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

2、创建一个实例

public class User {

    private Long id;
    private String username;
    private Date birthday;

    public User(Long id, String username) {
        this.id = id;
        this.username = username;
    }

    public User(Long id, String username, Date birthday) {
        this.id = id;
        this.username = username;
        this.birthday = birthday;
    }

    public User() {
    }

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    public Date getBirthday() {
        return birthday;
    }


    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

3、创建controller与启动类

@RestController
public class JsonController {

    //操作字符串
    @RequestMapping("/string")
    public String string(){
        return "字符串";
    }

    //对象
    @RequestMapping("/object")
    public User obj(){
        return new User(1L,"测试");
    }

    //时间
    @RequestMapping("/obj2")
    public User obj2(){
        return new User(2L,"ceshi2",new Date());
    }

    //数组
    @RequestMapping("/list")
    public List<User> list(){
        return Arrays.asList(new User(3L,"ceshi3",new Date()),
                new User(4L,"ceshi4",new Date()));
    }
}
@SpringBootApplication
public class JsonApplicationConfig
{
    public static void main( String[] args )
    {
        SpringApplication.run(JsonApplicationConfig.class);
    }
}

七、集成JDBC

1、导入依赖

     <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

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

2、和以前一样完成三层架构

3、配置文件链接数据库application.properties

spring.datasource.url = jdbc:mysql://localhost:3306/user
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

3、配置启动类:

@SpringBootApplication
@ComponentScan("cn.wutao.springboot")
public class UserApplicationConfig
{
    public static void main( String[] args )
    {
        SpringApplication.run(UserApplicationConfig.class);
    }
}

八、集成mybatis

1、导入依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- mysql 数据库驱动. -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--spring-boot mybatis依赖:-->
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.1.1</version>
</dependency>

2、和以前一样完成三层架构

3、配置文件:application.properties

spring.datasource.url = jdbc:mysql://localhost:3306/user
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

#可以配置别名
#mybatis.type-aliases-package=cn.wutao.springboot.domain.User

4、mapper.xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wutao.springboot.mapper.UserMapper">
    <select id="findAll" resultType="cn.wutao.springboot.domain.User">
        select * from t_user
    </select>
</mapper>

5、启动类

@SpringBootApplication
@MapperScan("cn.wutao.springboot.mapper")
public class MybatisApplicationConfig
{
    public static void main( String[] args )

    {
        SpringApplication.run(MybatisApplicationConfig.class);
    }
}

6、配置datasource

如果要配置自定义的dataSource类型 使用 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 指定

7、集成mybatis

  • 配置mybatis.mapper-locations
  • 配置别名mybatis.type-aliases-package (非必须)
  • 配置mybatis配置文件路径mybatis.config-location (非必须)
  • 配置类贴@MapperScan

 

九、其他配置:

1、配置文件对比:

      ①、ymal配置方式application.yml

            

        server:
          port: 7071

      ②、application.properties配置方式

        server.port=7070

 2、打包运行项目:

     ①、引入打包依赖:

<build>
    <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>utf-8</encoding>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
           <mainClass>cn.wutao.springboot.HelloApplicationConfig</mainClass> <!--主类启动类 包含main-->
            <layout>JAR</layout>
        </configuration>
    </plugin>
    </plugins>
    </build>

   ②、idea--maven project--选择打包模块--lifecycle--先clean-在package

   ③、项目target目录下生成jar包。打开所在目录cmd

   ④、cmd输入命令:java  -jar xxxxxx.jar 回车执行

3、多环境切换:

    ①、多文件配置:

          application-dev.yml(开发环境)

       

      server:
         port: 8081

          application-test.yml(测试环境)

              

        server:
          port: 8082

          application.yml(确定使用环境)

            

            spring:
              profiles:
                active: test

        ②、单文件配置:

             

        spring:
          profiles:
            active: test
        ---
        server:
          port: 7070
        spring:
          profiles: dev
        ---
        server:
          port: 7071
        pring:
          profiles: test

      ③、在运行时指定环境:

            

        java -jar -Dspring.profiles.active=dev   xxxxxxx.jar

4、事务配置

①、注解配置

  • @EnableTranstractionManager - 贴启动类上
  • @Transcational - 贴service上
  • @Service
    @Transactional(propagation = Propagation.SUPPORTS)
    public class UserService implements IUserService{
    
        @Autowired
        private IUserDao userDao;
    
        @Override
        @Transactional(readOnly = false)//只读
        public List<User> findAll() {
            return userDao.findAll();
        }
    }

     

③、xml配置

  • 创建xml 配置事务
  • 配置类导入xml配置 @ImportResource
  • <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           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.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    ">
        <!--事务管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!--配置aop-->
        <aop:config>
            <aop:pointcut id="curdPointcut" expression="execution(* cn.wutao.springboot.service.*.*(..))" />
            <aop:advisor   pointcut-ref="curdPointcut"  advice-ref="crudAdvice" />
        </aop:config>
    
        <!--配置事务增强-->
        <tx:advice transaction-manager="transactionManager" id="crudAdvice">
            <tx:attributes>
                <tx:method name="find*" read-only="true" />
                <tx:method name="get*" read-only="true" />
                <tx:method name="select*" read-only="true" />
                <tx:method name="query*" read-only="true" />
                <tx:method name="count*" read-only="true" />
                <tx:method name="load*" read-only="true" />
                <tx:method name="search*" read-only="true" />
                <tx:method name="*"  propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    
    </beans>

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值