美文网首页
Spring Boot项目搭建

Spring Boot项目搭建

作者: Luke_Hu | 来源:发表于2020-09-04 15:05 被阅读0次

    1. 创建项目,在pom.xml中添加依赖配置

    <!-- 添加父工程 -->
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.2.6.RELEASE</version>
    </parent>
    
    <!-- 设置JDK版本 -->
    <properties> 
        <java.version>1.8</java.version>
    </properties>
    
    <!-- 添加依赖 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    

    2. 创建Application入口类

    /**
     * spring boot工程都有一个启动引导类,这是工程的入口类
     * 并在引导类上添加@SpringBootApplication
     */
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

    3. 创建处理器Controller

    @RestController
    public class HelloController {
    
        @RequestMapping(value = "/hello", method = RequestMethod.GET)
        public String hello(){
            return "Hello, Spring Boot!";
        }
    }
    

    4. 使用Java代码配置数据库连接池,并在处理器Controller中注入并使用

    4.1 添加依赖

    <!--alibaba数据库连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.23</version>
    </dependency>
    

    4.2 创建数据库

    4.3 创建配置数据库连接参数的配置文件(.properties)

    jdbc.driverClassName=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/springboot_test
    jdbc.username=root
    jdbc.password=HT408706th
    

    4.4 编写配置类

    @Configuration
    @PropertySource("classpath:jdbc.properties")//指定配置文件路径
    public class JdbcConfig {
        //从配置文件中读取配置项
        @Value("${jdbc.url}")
        String url;
        @Value("${jdbc.driverClassName}")
        String driverClassName;
        @Value("${jdbc.username}")
        String username;
        @Value("${jdbc.password}")
        String password;
    
        //注册数据源到IOC容器中
        @Bean
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    }
    

    4.5将注册的DataSource注入处理器(测试是否配置成功)

    @Autowired
    private DataSource dataSource;
    

    5. 使用@ConfigurationProperties实现Spring Boot配置文件配置项读取和应用

    5.1 创建配置项类JdbcProperties类,在该类名上面添加@ConfigurationProperties;

    /**
     * ConfigurationProperties从applicationp配置文件中读取配置项
     * prefix表示配置项的前缀
     * 配置项类中的类变量名必须要与前缀之后的配置项名称保持 松散绑定(相同)
     */
    @ConfigurationProperties(prefix = "jdbc")
    public class JdbcProperties {
    
        private String url;
        private String driverClassName;
        private String username;
        private String password;
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public String getDriverClassName() {
            return driverClassName;
        }
    
        public void setDriverClassName(String driverClassName) {
            this.driverClassName = driverClassName;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    
    • 5.1.1 添加依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <!-- 不传递依赖 -->
        <optional>true</optional>
    </dependency>
    

    5.2 将jdbc.properties修改名称为application.properties;

    5.3 将JdbcProperties对象注入到JdbcConfig;

    @Configuration
    @EnableConfigurationProperties(JdbcProperties.class)
    public class JdbcConfig {
        @Bean
        public DataSource dataSource(JdbcProperties jdbcProperties) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        }
    }
    

    5.4 在方法上面使用@ConfigurationProperties;

    @Configuration
    public class JdbcConfig {
        @Bean
        @ConfigurationProperties(prefix = "jdbc")
        public DataSource dataSource() {
            return new DruidDataSource();
        }
    }
    

    6. springboot整合ssm

    6.1 使用lombok插件对实体类进行简化

    • 6.1.1 安装lombok插件
    • 6.1.2 添加lombok对应的依赖
    • 6.1.3 改造实体类,使用lombok注解
    /**
     * 在编译阶段会根据注解自动生成对应的方法;data包含get/set/hashCode/equals/toString等方法
     */
    @Data
    public class User {
        private Long id;
        private  String userName;
        private String password;
        private String name;
        private Integer age;
        private Integer sex;
        private Date birthday;
        private String note;
        private Date created;
        private Date updated;
    }
    
    

    6.2 springboot整合springmvc端口和静态资源

    • 6.2.1 修改项目Tomcat端口
    #修改Tomcat端口
    server.port=80
    
    • 6.2.2 springboot项目中静态资源可以放置在如下目录

    {"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

    6.3 在springboot项目中配置自定义springmvc拦截器

    • 6.3.1 编写拦截器(实现HandlerInterceptor)
    @Slf4j
    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.debug("这是MyInterceptor的preHandle方法");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            log.debug("这是MyInterceptor的postHandle方法");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            log.debug("这是MyInterceptor的afterCompletion方法");
        }
    }
    
    • 6.3.2 编写配置类,实现WebMvcConfigurer,在该类中添加各种组件
    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
    
        // 注册拦截器
        public MyInterceptor myInterceptor(){
            return new MyInterceptor();
        }
    
        // 添加拦截器到spring mvc拦截器
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
        }
    }
    

    6.4. springboot整合事务和连接池

    • 6.4.1 事务配置
      添加事务相关启动器依赖,mysql相关依赖
    <!-- 添加事务启动器依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- 添加mysql驱动依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    

    编写业务类UserService使用事务注解@Transactional

    @Service
    public class UserService {
    
        //根据id查询
        public User queryById(Long id){
            return new User();
        }
    
        //新增保存用户 添加事务注解
        @Transactional
        public void saveUser(User user){
            System.out.println("新增用户...");
        }
    }
    
    • 6.4.2 数据库连接池hikari配置(hikari是springboot自带的默认数据库连接池)
      在application配置文件中指定数据库相关参数
    #配置数据库连接池
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot_test
    spring.datasource.username=root
    spring.datasource.password=root
    

    6.5 springboot整合mybatis

    • 6.5.1 添加启动器依赖
    <!-- 添加mybatis启动器依赖 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>
    
    • 6.5.2 配置Mybatis:实体类别名包、日志、映射文件等
    #配置mybatis
    # 实体类别名包路径
    mybatis.type-aliases-package=com.emar.pojo
    # 映射文件路径
    #mybatis.mapper-locations=classpath:mappers/*.xml
    # 日志
    mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    
    • 6.5.3 配置MappperScan
    /**
     * spring boot工程都有一个启动引导类,这是工程的入口类
     * 并在引导类上添加@SpringBootApplication
     */
    @SpringBootApplication
    // 扫描mybatis所有的业务mapper接口
    @MapperScan("com.emar.mapper")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

    6.6 springboot整合通用mapper

    通用mapper可以实现自动拼接SQL语句;所有mapper都不需要编写SQL语句,提高开发效率。

    • 6.6.1 添加启动器依赖
    <!-- 通用mapper -->
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>2.1.5</version>
    </dependency>
    
    • 6.6.2 改造UserMapper集成Mapper<User>
    public interface UserMapper extends Mapper<User> {
    }
    
    • 6.6.3 修改启动引导类Application中的Mapper扫描注解
    /**
     * spring boot工程都有一个启动引导类,这是工程的入口类
     * 并在引导类上添加@SpringBootApplication
     */
    @SpringBootApplication
    // 扫描mybatis所有的业务mapper接口
    //@MapperScan("com.emar.mapper")
    @MapperScan("com.emar.mapper")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
    • 6.6.4 修改User实体类添加jpa注解
    /**
     * 在编译阶段会根据注解自动生成对应的方法;data包含get/set/hashCode/equals/toString等方法
     */
    @Data
    @Table(name = "tb_user")
    public class User {
        @Id
        //主键回填
        @KeySql(useGeneratedKeys = true)
        private Long id;
    
        //user_name --> userName,若数据库字段名和属性名不一致,可使用@Column注解
    //    @Column(name = "adc")
        private  String userName;
        private String password;
        private String name;
        private Integer age;
        private Integer sex;
        private Date birthday;
        private String note;
        private Date created;
        private Date updated;
    }
    
    • 6.6.5 改造UserService实现业务功能
    @Service
    public class UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        //根据id查询
        public User queryById(Long id){
            return userMapper.selectByPrimaryKey(id);
        }
    
        //新增保存用户 添加事务注解
        @Transactional
        public void saveUser(User user){
            System.out.println("新增用户...");
            userMapper.insertSelective(user);
        }
    }
    

    7. springboot整合测试

    7.1 改造HelloController,注入UserService利用其方法实现查询

    @RestController
    public class HelloController {
    
        @Autowired
        private DataSource dataSource;
    
        //注入业务对象
        @Autowired
        private UserService userService;
    
        /**
         * 根据用户id查询用户
         * @param id 用户id
         * @return 用户
         */
        @GetMapping("/user/{id}")
        public User queryById(@PathVariable Long id){
            return userService.queryById(id);
        }
    
        @RequestMapping(value = "/hello", method = RequestMethod.GET)
        public String hello(){
            System.out.println(dataSource);
            return "Hello, Spring Boot!";
        }
    }
    

    7.2 启动项目测试http://localhost/user/用户id

    8. springboot整合Junit

    8.1 添加启动器依赖spring-boot-starter-test

    <!-- 单元测试依赖 -->
    <dependency>
        <groupId>org.wildfly.swarm</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>1.0.0.Alpha2</version>
    </dependency>
    

    8.2 在springBoot项目中编写测试类,则必须要在类上面添加@SpringBootTest注解

    9. spring Boot整合redis

    9.1 添加启动器依赖spring-boot-starter-data-redis

    <!-- redis依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    

    9.2 application配置文件中修改redis的连接参数(redis需要启动)

    #配置redis
    spring.redis.host=localhost
    spring.redis.port=6379
    

    9.3 编写测试类应用RedisTemplate操作redis中的5种数据类型(string、hash、list、set、sorted set)

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class RedisTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        public void test(){
            //string 字符串
    //        redisTemplate.opsForValue().set("str", "emar");
            redisTemplate.boundValueOps("str").set("emar");
            System.out.println("str = " + redisTemplate.opsForValue().get("str"));
    
            //hash 散列
            redisTemplate.boundHashOps("e_key").put("name", "emar");
            redisTemplate.boundHashOps("e_key").put("age", 24);
            //获取所有域
            Set set = redisTemplate.boundHashOps("e_key").keys();
            System.out.println("hash散列的所有域:" + set);
            //获取所有值
            List list = redisTemplate.boundHashOps("e_key").values();
            System.out.println("hash散列的所有域的值:" + list);
    
            //list列表
            redisTemplate.boundListOps("l_key").leftPush("c");
            redisTemplate.boundListOps("l_key").leftPush("b");
            redisTemplate.boundListOps("l_key").leftPush("a");
            //获取全部元素
            List list1 = redisTemplate.boundListOps("l_key").range(0, -1);
            System.out.println("list列表的所有元素:" + list1);
    
            //set集合
            redisTemplate.boundSetOps("s_key").add("a", "b", "c");
            Set set1 = redisTemplate.boundSetOps("s_key").members();
            System.out.println("set集合中的所有元素:" + set1);
    
            //sorted set有序集合
            redisTemplate.boundZSetOps("z_key").add("a", 30);
            redisTemplate.boundZSetOps("z_key").add("b", 20);
            redisTemplate.boundZSetOps("z_key").add("c", 10);
            Set set2 = redisTemplate.boundZSetOps("z_key").range(0, -1);
            System.out.println("zset有序集合中的所有元素:" + set2);
        }
    }
    

    10. spring Boot项目部署

    10.1 需要添加打包组件,将项目中的资源、配置、依赖包打到一个jar包中;可以使用maven的package;

    <build>
        <plugins>
            <!-- 打jar包时如果不配置该插件,打出来的jar包没有清单文件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    

    10.2 部署:java -jar 包名

    在项目目录的target下找到jar包,启动命令行:java -jar jar包文件

    相关文章

      网友评论

          本文标题:Spring Boot项目搭建

          本文链接:https://www.haomeiwen.com/subject/nkbzsktx.html