springBoot创建MVC项目入门(一)

官网:https://spring.io/projects/spring-boot

https://spring.io/guides

中文翻译文档参考:

https://legacy.gitbook.com/@docshome

https://www.w3cschool.cn/springboot/springboot-w7c2245h.html

springBoot大大简化了spring的很多烦人的xml配置,但是有时程序的默认配置或加载配置的优先级总是让人很头疼,好多时候不是代码有问题,而是配置的文件名不规则,或者对应的目录结构不符合它加载模式,导致文件识别不了或识别异常。

接下来就其基本的默认配置的加载几部分特定文件识别等做简单的介绍,同时对配置属性文件异常时提供一个简单的定位方法。

      springboot 的配置基本可以在spring-boot-autoconfigure对应的jar包中看到,对于默认的配置读取,设置以及对应的加载过程需要做简单了解,否则无法准确知道属性的值,特别是刚入门不久。

一、项目创建

       使用IDE或者进入https://start.spring.io/ ;选择对应的配置,然后下载对应的压缩包,解压后导入IDE。

二、pox.xml

      根据项目需要来添加对应的依赖,案例为wed,mybatis项目。

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

三、属性文件

SpringApplication 从以下位置的 application.properties 文件中加载属性(properties),并将它们添加到 Spring Environment 中:

  1. 当前目录的 /config 子目录
  2. 当前目录
  3. classpath 上的 /config
  4. classpath 根路径

列表按序号优先级排序,序号越小,优先级越高,同时也可以使用yml文件(YamlPropertiesFactoryBean 将 YAML 加载为 PropertiesYamlMapFactoryBean 将 YAML 加载为 Map),代替properties文件,属性文件的优先级更高。

如果您不喜欢 application.properties 作为配置文件名,则可以通过指定 spring.config.name 环境属性来切换到另一个文件名。您还可以使用 spring.config.location 环境属性来引用一个显式位置(以逗号分隔的目录位置或文件路径列表)。以下示例展示了如何指定其他文件名:

spring.config.name=projectPropertiesName

虽然可以自定义属性文件名,但是做好使用application-XX.properties的命名规则,具体可参见springboot配置解析源码。

默认情况下,配置的位置为 classpath:/,classpath:/config/,file:./,file:./config/。生成的搜索顺序如下:

  1. file:./config/
  2. file:./
  3. classpath:/config/
  4. classpath:/
  5. spring.config.location 配置自定义配置位置时,默认位置配置将被替代,若配置后优先级变化。

  application-{profile}.propertiesEnvironment 有一组默认配置文件(默认情况下为 default),如果未设置激活的(active)profile,则使用这些配置文件。换句话说,如果没有显式激活 profile,则会加载 application-default.properties 中的属性。

Thymeleaf为springboot自带的显示架构,使用了XML DOM解析器,因此它并不适合于处理大规模的XML文件。引用模板后的配置如下,需要注意的是对应的模板文件需要放在对应的source的目录下。

spring.thymeleaf.mode=HTML;

spring.thymeleaf.encoding=utf-8;

application.yml  (properties类似)通用配置文件如下:

# 项目相关配置
ruoyi:
  # 名称
  name: RuoYi
  # 版本
  version: 3.2.0
  # 版权年份
  copyrightYear: 2019
  # 文件上传
  profile: D:/profile/
  # 获取ip地址开关
  addressEnabled: true
# 开发环境配置
server:
  # 服务端口
  port: 80
  servlet:
    # 项目contextPath
    context-path: /
  tomcat:
    # tomcat的URI编码
    uri-encoding: UTF-8
    # tomcat最大线程数,默认为200
    max-threads: 800
    # Tomcat启动初始化的线程数,默认值25
    min-spare-threads: 30
# 日志配置
logging:
  level:
    com.ruoyi: debug
    org.springframework: WARN
    org.spring.springboot.dao: debug
# 用户配置
user:
  password:
    # 密码错误{maxRetryCount}次锁定10分钟
    maxRetryCount: 5
# Spring配置
spring:
  # 模板引擎
  thymeleaf:
    mode: HTML
    encoding: utf-8
    # 禁用缓存
    cache: false
  # 资源信息
  messages:
    # 国际化资源文件路径
    basename: i18n/messages
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  profiles: 
    active: druid
  # 文件上传
  servlet:
     multipart:
       max-file-size:  30MB
       max-request-size:  30MB
  # 服务模块
  devtools:
    restart:
      # 热部署开关
      enabled: true
# MyBatis
mybatis:
    # 搜索指定包别名
    typeAliasesPackage: com.ruoyi
    # 配置mapper的扫描,找到所有的mapper.xml映射文件
    mapperLocations: classpath*:mapper/**/*Mapper.xml
    # 加载全局的配置文件
    configLocation: classpath:mapper/mybatis-config.xml
# PageHelper分页插件
pagehelper: 
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql 
# Shiro
shiro:
  user:
    # 登录地址
    loginUrl: /login
    # 权限认证失败地址
    unauthorizedUrl: /unauth
    # 首页地址
    indexUrl: /index
    # 验证码开关
    captchaEnabled: true
    # 验证码类型 math 数组计算 char 字符
    captchaType: math
  cookie:
    # 设置Cookie的域名 默认空,即当前访问的域名
    domain: 
    # 设置cookie的有效访问路径
    path: /
    # 设置HttpOnly属性
    httpOnly: true
    # 设置Cookie的过期时间,天为单位
    maxAge: 30
  session:
    # Session超时时间(默认30分钟)
    expireTime: 30
    # 同步session到数据库的周期(默认1分钟)
    dbSyncPeriod: 1
    # 相隔多久检查一次session的有效性,默认就是10分钟
    validationInterval: 10
# 防止XSS攻击
xss: 
  # 过滤开关
  enabled: true
  # 排除链接(多个用逗号分隔)
  excludes: /system/notice/*
  # 匹配链接
  urlPatterns: /system/*,/monitor/*,/tool/*

在设置注存数据库时配置如下:

# 数据源配置
spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        druid:
            # 主库数据源
            master:
                url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
                username: root
                password: password
            # 从库数据源
            slave:
                # 从数据源开关/默认关闭
                enabled: false
                url: 
                username: 
                password: 
            # 初始连接数
            initialSize: 5
            # 最小连接池数量
            minIdle: 10
            # 最大连接池数量
            maxActive: 20
            # 配置获取连接等待超时的时间
            maxWait: 60000
            # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一个连接在池中最小生存的时间,单位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一个连接在池中最大生存的时间,单位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置检测连接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter: 
                enabled: true
            statViewServlet:
                enabled: true
                # 设置白名单,不填则允许所有访问
                allow:
                url-pattern: /monitor/druid/*
            filter:
                stat:
                    enabled: true
                    # 慢SQL记录
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: true
                wall:
                    config:
                        multi-statement-allow: true

主存复制数据库设置参见:https://blog.csdn.net/u010098331/article/details/50828820

三、持久化方式

底层数据库以mysql为例。

Spring Data JPA步骤:(https://spring.io/guides/gs/accessing-data-jpa/

1、创建一个添加了JPA包的springboot项目;

作者使用了Spring Tool Suite(https://spring.io/guides/gs/sts/).创建,具体过程参见官网。

<!--JPA支持-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2、定义实体类entity

package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity  //标记为数据库实体,数据库的表明和实体名相同也可使用@Table
public class Customer {

    @Id  //数据库字段,主键自增
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

示例省略了setter和getter方法。

3、创建简单的查询

a、创建查询接口

package hello;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);
}

CustomerRepository 继承自 CrudRepository接口. 实体中的id等参数将和CrudRepository对应接口的参数一致,通过这种继承,已经实现了部分封装好的方法,也可以在以上接口中用户自定一相关查询,然后在实现上述接口,这样就会很好的实现JPA的强大功能。

使用Dao---->service---->controller结构时,对应的三层结构实现类注解为:

DaoImpl( @Repository, @Autowired)  :实现底层数据库交互查询,

ServiceImpl(@Service  @Autowired ):实现业务逻辑处理,调用DaoImpl层数据交互

Controller(@ModelAttribute/@RestController/@Controller/@RequestMapping("/jdbc/account")/@Autowired/@PathVariable("id") )   : 界面业务跳转,请求处理,调用sevice层业务逻辑。

3、创建appication启动组件

package hello;

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

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

	private static final Logger log = LoggerFactory.getLogger(Application.class);

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

	@Bean
	public CommandLineRunner demo(CustomerRepository repository) {
		return (args) -> {
			// save a couple of customers
			repository.save(new Customer("Jack", "Bauer"));
			repository.save(new Customer("Chloe", "O'Brian"));
			repository.save(new Customer("Kim", "Bauer"));
			repository.save(new Customer("David", "Palmer"));
			repository.save(new Customer("Michelle", "Dessler"));

			// fetch all customers
			log.info("Customers found with findAll():");
			log.info("-------------------------------");
			for (Customer customer : repository.findAll()) {
				log.info(customer.toString());
			}
			log.info("");

			// fetch an individual customer by ID
			repository.findById(1L)
				.ifPresent(customer -> {
					log.info("Customer found with findById(1L):");
					log.info("--------------------------------");
					log.info(customer.toString());
					log.info("");
				});

			// fetch customers by last name
			log.info("Customer found with findByLastName('Bauer'):");
			log.info("--------------------------------------------");
			repository.findByLastName("Bauer").forEach(bauer -> {
				log.info(bauer.toString());
			});
			// for (Customer bauer : repository.findByLastName("Bauer")) {
			// 	log.info(bauer.toString());
			// }
			log.info("");
		};
	}

}

@SpringBootApplication为复合注解,包含以下内容:

@Configuration   标记为应用程序上下文的bean定义源

 @EnableAutoConfiguration  告诉SpringBoot根据类路径设置、其他bean和各种属性设置开始添加bean。

@ComponentScan  告诉spring在hello包中查找其他组件、配置和服务,允许它查找控制器。

        首先,它从Spring应用程序上下文中获取customerrepository。然后它保存了一些客户对象,演示了save()方法并设置了一些要使用的数据。接下来,它调用findall()从数据库中获取所有客户对象。然后调用findone()根据其ID获取单个客户,最后调用findbylastname()查找姓氏为“bauer”的所有客户。

    默认情况下,SpringBoot将启用JPA存储库支持,并查看@SpringBootApplication所在的包(及其子包)。如果配置中的JPA存储库接口定义位于不可见的包中,则可以使用@enableJParepositiones及其类型safe basePackageClass=myrepository.class参数指出备用包。所以项目的文档目录结构需要特别注意,相关文件或配置名需要特定。

建立完毕后可编译为可执行jar文件:

If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with .

/mvnw clean package. Then you can run the JAR file:

java -jar target/gs-accessing-data-jpa-0.1.0.jar

Mybatis 持久化:

        我们项目的结构基本不变。

配置文件添加依赖:

<!--MyBatis支持-->
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.2.0</version>
</dependency>
Mybatis可以采用两种方式进行编写,一种是基于xml的配置方式,一种是基于注解的方式。

@Mapper
public interface AccountMapper {
    @Insert("INSERT INFO account(name,money) VALUES(#{name},#{money})")
    int add(@Param("name")String name,
            @Param("money")double money);

    @Update("UPDATE account SET name = #{name}, money = #{money} WHERE id = #{id}")
    int update(@Param("name") String name, @Param("money") double money, @Param("id") int  id);

    @Delete("DELETE FROM account WHERE id = #{id}")
    int delete(int id);

    @Select("SELECT id, name AS name, money AS money FROM account WHERE id = #{id}")
    Account findAccount(@Param("id") int id);

    @Select("SELECT id, name AS name, money AS money FROM account")
    List<Account> findAccountList();
}

Dao层的实现使用注解时如上所示。

基于xml配置文件:

public interface AccountMapper1 {
    int update(@Param("money") double money, @Param("id") int  id);
}
首先需要写一个接口,然后在application中添加配置,由于我们的配置,后缀名必须为Mapper.xml才可以被扫描到:

mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml
mybatis.type-aliases-package=com.jinwen.www.MYBATIS.bean

注意,命名空间那里,需要填自己的,简单的一个update,做完这几步,就可以了。

参考文档:https://www.cnblogs.com/wangxiaomei/p/8885470.html   https://blog.csdn.net/fyhailin/article/details/79413864

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值