Spring框架介绍和使用

Spring框架是开源的轻量级Java应用开发框架

1.核心概念

  • 控制反转(IOC)

     Spring通过ioc容器管理对象的创建和依赖关系,不需要手动创建对象和管理依赖,而是由容器自动注入,降低了组件间的耦合度

  • 面向切面编程思想(AOP)

        Spring 支持 AOP,允许将横切关注点(如日志、事务、安全)与业务逻辑分离,以非侵入式的   方式增强代码功能,提高代码复用性。

        AOP 面向方面(切面)编程 AOP 是 OOP 的延续,是 Aspect Oriented Programming 的缩          写 意思是面向方面(切面)编程。 注:OOP(Object-Oriented Programming ) 面向对象编程

    2.Spring框架的体系结构

    Spring 框架由多个模块组成,覆盖了企业级应用开发的各个层面:
    • 核心容器(Core Container):提供 IoC 和依赖注入功能,是 Spring 的基础。
    • AOP 和设备支持:实现面向切面编程和对设备(如邮件、调度)的支持。
    • 数据访问与集成:支持与数据库(如 JDBC、Hibernate)、消息队列(如 JMS)的集成。
    • Web 模块:包含 Spring MVC,用于构建 Web 应用和 RESTful 服务。
    • 消息(Messaging):支持消息驱动的异步通信。
    • 测试模块(Test):提供测试支持,简化单元测试和集成测试。

    3. 主要特点

    • 轻量级:框架本身体积小,对系统资源消耗低。
    • 松耦合:通过 IoC 和接口编程,减少组件间的直接依赖。
    • 一站式解决方案:覆盖从配置、数据访问到 Web 开发的全流程,可集成其他框架(如 MyBatis、Hibernate)。
    • 声明式编程:通过注解或配置文件简化事务、安全等逻辑的编写。
    • 强大的生态系统:Spring Boot、Spring Cloud 等衍生项目进一步简化了微服务、云原生应用的开发。

    4. 优势与应用场景

    • 简化开发:减少样板代码,提高开发效率。
    • 灵活扩展:支持插件化设计,可根据需求选择模块。
    • 企业级支持:适用于构建大型分布式系统、Web 应用、微服务等。
    • 社区活跃:拥有庞大的开发者社区和丰富的学习资源。

    5. 入门与学习

    Spring 框架通常通过 XML 配置或注解(如 @Autowired@Controller)来使用。对于初学者,建议从 Spring Core 和 Spring MVC 开始,逐步学习 AOP、数据访问等高级功能。结合 Spring Boot 可进一步体验 “开箱即用” 的便利。

    总之,Spring 框架凭借其灵活性、可扩展性和强大的生态,成为 Java 企业级开发的首选框架,帮助开发者更高效地构建健壮、可维护的应用程序

    SpringBoot

    SpringBoot用来简化Spring的应用开发,约定大于配置 ,去繁从简,just run就可以创建一个独立的产品级的应用

    SpringBoot的优点

    • 快速创建独立运行的Spring项目以及主流框架的集成
    • 使用嵌入式的Servlet容器,应用不用打成WAR包
    • straters的自动依赖和版本控制
    • 大量自动配置,简化开发,还可以修改默认值
    • 无需配置XML,无代码生成,开箱即用

    下面是建立一个SpringBoot项目进行简单的增删改查

    这里jdk可以选择1.8或者更高的都可以




    下面是pom.xml的依赖,数据库的依赖根据自己下载的版本调整

    <dependencies>
            <!-- Web依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!-- MyBatis PageHelper 插件,用于分页查询(可选) -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.4.6</version>
            </dependency>
            <!-- Spring Boot依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <!-- Mybatis依赖-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</version>
            </dependency>
            <!-- Mysql连接依赖-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.33</version>
    
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
        </dependencies>

    下面是application.yml的配置文件 或者用propreties也可以修改后缀名就行了,数据库的名字和用户名还有密码都改成自己的

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
        username: root
        password: 123456

    在com.view.demo2包下面建四个包,分别是控制层(controller)  实体类(pojo) 业务逻辑层 (service) mapper(数据访问层) 然后分别建四个类



    package com.view.demo2.controller;
    
    import com.view.demo2.pojo.User;
    import com.view.demo2.service.UserService;
    import org.apache.ibatis.annotations.Delete;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("api/users")
    public class UserController {
        @Autowired
        private UserService userService;
    
       @GetMapping
        public ResponseEntity <List<User>>  getUserAll(){      //封装成responseEntity对象返回
           List<User> users = userService.getUserAll();
           return new ResponseEntity<>(users, HttpStatus.OK);
       }
       @GetMapping("{id}")
        public ResponseEntity <User> getUserById(@PathVariable Long id){
           User user = userService.getUserById(id);
           if (user != null){
               return new ResponseEntity<>(user ,HttpStatus.OK);
           }
           return new ResponseEntity<>(user, HttpStatus.OK);
       }
       @PutMapping
        public ResponseEntity <User>  updateUser(@RequestBody User user){
           userService.updateUser(user);
           return new ResponseEntity<>(user, HttpStatus.OK);
       }
       @PostMapping
        public ResponseEntity <User> insertUser(@RequestBody User user){
           userService.insertUser(user);
           return new ResponseEntity<>(user , HttpStatus. OK);
       }
       @Delete("id")
        public ResponseEntity <User> deleteUser(@PathVariable Long id){
           userService.deleteUser(id);
           return new ResponseEntity<>(HttpStatus.NO_CONTENT);
       }
    }
    

    package com.view.demo2.mapper;
    
    import com.view.demo2.pojo.User;
    import org.apache.ibatis.annotations.*;
    
    import java.util.List;
    
    @Mapper
    public interface UserMapper {
        //添加数据
        //增
        @Insert("INSERT INTO users(username age) VALUES (#{username}, #{age})")
        @Options(useGeneratedKeys = true, keyProperty = "id")  //Options用于新增之后获取数据库的主键值
        void insertUser(User user);
        //删除数据
        //删
        @Delete("DELETE FROM users WHERE id=(#{id})")
        void  deleteUser(Long id);
        //修改数据
        //改
        @Update("UPDATE users SET (#{username},#{age}), WHERE(#{id})")
        void updateUser(User user);
        //查询数据
        //查
        @Select("SELECT*FROM users")
        List<User> getUserAll();
    
        //根据id查询数据
        @Select("SELECT*FROM users WHERE id=(#{id})")
        User getUserById(Long id);
    
    }
    

    package com.view.demo2.pojo;
    
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    //生成有参无参get和set
    @Entity
    public class User {
    
        @Id
        @GeneratedValue  (strategy = GenerationType.IDENTITY)
    
        private Long id;
        private String name;
        private int age;
    
        public User(){
    
        }
    
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
    }
    

    package com.view.demo2.service;
    
    
    import com.view.demo2.mapper.UserMapper;
    import com.view.demo2.pojo.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    @Service
    public class UserService {
        @Autowired
        private UserMapper userMapper;
        //查询所有的方法
        public List<User> getUserAll() {
            return userMapper.getUserAll();
        }
        //根据id查询的方法
        public User getUserById(Long id) {
            return userMapper.getUserById(id);
        }
        //新增的方法
        public void insertUser(User user) {
            userMapper.insertUser(user);
        }
        //修改的方法
        public void updateUser(User user) {
            userMapper.updateUser(user);
        }
        //删除的方法
        public void deleteUser(Long id) {
            userMapper.deleteUser(id);
        }
    
    
    }
    

    然后在启动器里面运行


    下面是运行结果  在浏览器输入网址 http://localhost:8080/api/users

    如果你的应用程序启动失败,注册的 FailureAnalyzers 会尝试提供一个专门的错误信息提示和具体的解决办法。 例如,如果你在端口 8080 上启动一个网络应用,而该端口已经被使用,你应该看到类似于下面的信息。

    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    Description:
    
    Embedded servlet container failed to start. Port 8080 was already in use.
    
    Action:
    
    Identify and stop the process that is listening on port 8080 or configure this application to listen on another port.

    SpringCloud

    Spring Cloud 是一个为开发人员提供了一系列工具来快速构建分布式系统中常用模式的框架

    1.核心功能

    服务发现与注册:

    在分布式系统中,服务数量众多,服务器之间需要相互调用然而服务发现和注册功能能让服务信息注册到注册中心当中,并能从注册中心中获取其他服务的注册地址和信息 


    配置管理:

    在分布式环境中各个服务器的配置问题也是个难题,Spring Cloud Config 能够使服务器的配置集中管理并刷新到最新配置

    负载均衡:

    负载均衡能够将服务的请求均匀的发送到各个服务器的实例中,大大提高了性能和可用性

    断路器:

    当某个服务发生故障的时候,断路器能快速切断对该服务的调用,大大提高了系统的稳定性

    API网关:

    API网关作为系统的统一出口,对所有的请求进行路由和过滤,可以实现权限验证,限流和日志记录等功能

    消息总线:

    消息总线可以在分布系统的各个服务中实现消息传输,实现动态配置刷新和消息广播

    2.应用场景

    • 微服务架构: SpringClou的各个组件能够帮助我们更快的创建和管理微服务项目,实现注册,熔断,发现,调用等功能,使微服务框架的开发和维护更高效
    • 分布式系统:在分布式系统中配置管理,负载均衡,通信这些都是开发的难点,但SpringCloud提供的方案可以有效的解决这些问题

    3.优势

    • 简化开发:提供了大量的开箱即用的组件和工具,减少了开发人员的工作量,加快了开发速度。
    • 集成性好:与 Spring Boot 无缝集成,可利用 Spring Boot 的自动配置特性,降低了学习成本和配置难度。
    • 社区活跃:拥有庞大的社区支持,有丰富的文档和开源项目可供参考,遇到问题容易找到解决方案

    下面是一个简单的SpringCloudEureka示例

    创建一个SpringBoot项目并加入以下依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
    在启动类上添加@EnableEurekaServer注解
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    @SpringBootApplication
    @EnableEurekaServer
    public class EurekaServerApplication {
        public static void main(String[] args) {
            SpringApplication.run(EurekaServerApplication.class, args);
        }
    }
    在Appclition propreties中配置Eureka
    server.port=8761
    eureka.client.register-with-eureka=false
    eureka.client.fetch-registry=false
    创建另一个 Spring Boot 项目,添加以下依赖:
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
    在启动类上添加@EnableEurekaClient注解:
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.client.EnableEurekaClient;
    
    @SpringBootApplication
    @EnableEurekaClient
    public class ServiceProviderApplication {
        public static void main(String[] args) {
            SpringApplication.run(ServiceProviderApplication.class, args);
        }
    }

    application.properties中配置服务提供者

    server.port=8080
    spring.application.name=service-provider
    eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
    创建一个控制类
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
        @GetMapping("/hello")
        public String hello() {
            return "Hello, Spring Cloud!";
        }
    }

    然后再运行启动类在浏览器中打开网址

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值