spring 到SpringBoot

5 篇文章 0 订阅
3 篇文章 0 订阅
本文回顾了Spring的基本概念,包括IOC、DI、AOP,介绍了从XML配置到注解配置的转变,详细讲解了SpringBoot的特点和优势。内容涵盖Spring的配置类、自动扫描、Bean详解、依赖注入以及条件化配置。此外,还探讨了SpringBoot的HelloWorld示例及特点,如注解配置、快速开发、内嵌Tomcat等。
摘要由CSDN通过智能技术生成

非常重要的编码规范

1.包名:全小写,多个单词用“_”隔开,不准驼峰或数字开头

2.类名:首字母大写,驼峰

3.方法名:首字母小写,驼峰

4.代码块“{}”中的内容要有缩进,同级代码要左对齐 , 注释和代码左对齐

spring 到SpringBoot

一.Spring回顾

1.基本概念

1.1.SpringBoot介绍

Spring Boot是其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

1.2..JavaConfig基本概念

Spring注解式编程也叫JavaConfig,即通过一个Java类来配置Spring,或者说把以前xml中配置的内容搬到了一个Java类中,这个类就是Spring的配置类,和以前的XML有相同的作用。

2.Spring回顾

2.1.IOC基本概念

控制反转,我们不需要手工去管理Bean,而是将Bean的创建,初始化,销毁等等工作全部交给Spring管理 。解放我们的工作量。

2.2.DI基本概念

依赖注入,既然Bean的管理交给了Spring,那么Bean之间的依赖关系也需要Spring去维护,DI指定就是Bean与Bean之间的依赖注入。

2.3.AOP基本概念

面向切面编程实现 ,可以看做是对面向对象的补充,面向切面指的是把多个Bean看成一个面,使用横切技术可以让功能(业务)作用于多个Bean , 使用AOP可以实现程序代码的解耦,公共代码的统一抽取和封装等等。Aop的原理是动态代理。

2.4.XML配置IOC

1.创建项目
2.导入依赖

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
    </dependencies>
3.创建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<!--  //5.把这类在 applicationContext.xml 配置成Bean-->
  <bean id="myBean" class="springboot001._01_xml_ioc.Mybean01">
  </bean>
</beans>

4.创建一个简单的类 MyBean

public class MyBean {
}
5.把这类在 applicationContext.xml 配置成Bean
6.编写测试类:让Spring加载applicationContext.xml 配置文件,获取容器  - ClassPathXmlApplicationContext
7.获取MyBean

package springboot001._01_xml_ioc;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlTest {

    @Test
    public void testMyBean(){
        //6.编写测试类:让Spring加载applicationContext.xml 配置文件,获取容器
        //针对于classpath下的xml配置的 Spring容器上下文对象
        ClassPathXmlApplicationContext classPathXmlApplicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        //7.获取MyBean
        Mybean01 bean = classPathXmlApplicationContext.getBean(Mybean01.class);
        System.out.println(bean);

    }
}

2.5总结

ClassPathXmlApplicationContext//加载配置文件,拿到Spring容器

二.注解方式配置IOC

操作步骤

1.创建新的包 

2.创建一个类作为Spring的配置类

/**
 * Spring的配置类 相当于是:applicationContext.xml
 * @Configuration :Spring的配置标签,标记改类是Spring的配置类
 */
@Configuration
public class MyApplicationConfig {

    /**
     * @Bean : Springbean的定义标签 ,标记方法返回的对象交给Spring容器管理
     */
    @Bean
    public MyBean02 myBean(){
        return new MyBean02();
    }
}

  1. 创建一个普通的类作为bean(MyBean)

同1

  1. 在配置类中,配置Bean
     
  2. 编写测试:加载配置类 ,获取容器 ,获取MyBean

public class MyJavaConfigTest {

    @Test
    public void test(){
        //加载配置文件,拿到Spring容器
        ApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(MyApplicationConfig.class);

        //通过容器获取Mybaean
        MyBean02 bean = applicationContext.getBean(MyBean02.class);
        System.out.println(bean);
    }
}

总结

  1. @Configuration加了这个注解的类就相当于传统的一个applicationContext-xxx.xml    
  2. @Bean Springbean的定义标签 ,标记方法返回的对象交给Spring容器管理

加上这个标签相当于<bean id=”  ” class=” ”>

  1. AnnotationConfigApplicationContext对象拿配置类的字节码文件

三.ComponentScan自动扫描

@ComponentScan是ioc组件自动扫描,相当于是 <context:component-scan base-package=* 默认扫描当前包及其子包 中打了 @Service , @Controller , @Component , @Repository其中一个注解的 类自动交给Spring管理;也可以通过 basePackages 属性指定扫描的包路径。

 

@Configuration
@ComponentScan("包名")
public class ApplicationConfig {
}

注意:如果使用了自动扫描 ,那么配置类中就不要去配置@Bean

@Configuration
public class ApplicationConfig {

    /**
     * beanid :就是方法的名字“myBean”
     * beanname: 通过 @Bean(name = "myBean") 指定
     *  init-method初始方法: @Bean(initMethod = "") 指定
     *  destroy-method销毁方法:@Bean(destroyMethod = "")指定
     *  lazy-init="false"懒初始化: 通过标签 @Lazy(value=false) 指定
     *  scope="singleton"单例: 通过 @Scope(value="singleton")指定
     */
    @Bean(name = "myBean",initMethod = "init",destroyMethod = "destroy")
    //@Lazy(value=false)
    //@Scope(value="singleton")
    public MyBean myBean(){
        MyBean myBean = new MyBean();
        return myBean;
    }
}

四.Bean的详解

1.Bean的属性介绍

我们以前使用Spring使用xml进行配置,如下:

 <bean id="myBean"
          name="myBean004"
          init-method=""
          destroy-method=""
          lazy-init="false"
          scope="prototype"
          class="cn.itsource._01_xml_ioc.MyBean">
        ...
    </bean>

那么在JavaCong中如何配置Bean的各种属性?

1.1.Bean的id

那么在JavaCong中,方法名就是Bean的id

1.2.Bean的name

可以通过 @Bean标签的name属性指定

1.3.生命周期方法

init-method初始方法: @Bean(initMethod = "") 指定

destroy-method销毁方法:@Bean(destroyMethod = "")指定

1.4.Bean的Scope

单利多利,通过 @Scope("prototype")指定

1.5.懒初始化:

lazy-init="false"懒初始化: 通过标签 @Lazy(value=false) 指定

@Configuration
@ComponentScan(basePackages = "springboot001._04_bean_detail")
public class ApplicationConfig04 {
    /**
     * beanid :就是方法的名字“myBean”
     * beanname: 通过 @Bean(name = "myBean") 指定
     *  init-method初始方法: @Bean(initMethod = "") 指定
     *  destroy-method销毁方法:@Bean(destroyMethod = "")指定
     *  lazy-init="false"懒初始化: 通过标签 @Lazy(value=false) 指定
     *  scope="singleton"单例: 通过 @Scope(value="singleton")指定
     */
    @Bean(name = "myBean004",initMethod = "init",destroyMethod = "destroy")
    @Lazy(value=false)  //false不使用懒加载
    @Scope(value="singleton")
    public MyBean04 myBean(){
        MyBean04 myBean = new MyBean04();
        return myBean;
    }
}

2.定义Mybean的init和destroy方法

public class MyBean04 {
    String name = "zs";
    public MyBean04() {
        System.out.println("无参构造被调用了");
        this.name="无参构造";
    }
    public MyBean04(String name) {
        this.name = name;
    }
    public void init() {
        this.name = "初始化实例";
        System.out.println("初始化实例....");
    }
    public void destroy() {
        System.out.println("销毁实例....");
    }
}

 

3.Spring的Test

上面的案例中我们的是使用的Junit的测试 ,在很多场景下Junit测试不能满足我们的需求,比如Junit测试会导致Bean的销毁方法没办办法正常管理,所以我们需要用到Spring的测试。

//使用Spring的Test ,不要直接用Junit的Test
//@ContextConfiguration(classes = ApplicationConfig.class) :加载Spring的配置类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfig.class)
public class JavaConfigTest {

    @Autowired
    private MyBean myBean;

    @Test
    public void testMyBean() throws Exception{
//        MyBean myBean2= new MyBean("xzc");
//        MyBean myBean3= new MyBean();
        System.out.println("myBean.name  "+myBean.name);
//        System.out.println("myBean2.name  "+myBean2.name);
//        System.out.println("myBean3.name  "+myBean3.name);
    }
}

 

总结

1.使用Spring的测试之后,就不要再使用new AnnotationConfigApplicationContext这种方式

2.@ContextConfiguration标签后面跟的是配置类的字节码

3.注入是先调用无参构造然后调用init初始化方法的

五.依赖注入

我们以前使用Spring使用xml进行配置,我们除了定义Bean而外还会给Bean进行依赖对象的注入,如下:

 <bean id="myBean"
         ...
         class="">
        <property name="username" value="zs" />
        <property name="OtherBean" ref="OtherBean" />
    </bean>

1.操作步骤

1.创建BaseBean类,BaseBean中有OtherBean字段

@Data
public class BaseBean {
    String name = "BaseBean";
    OtherBean otherbean = null;
}

2.创建OtherBean类

@Data
public class OtherBean {
    String name = "我是OtherBean";
}

3.定义MyBean,OtherBean并把OtherBean设置给MyBean

@Configuration
public class ApplicationConfig05 {

    @Bean
    public BaseBean BaseBean(OtherBean otherbean){
        BaseBean baseBean=new BaseBean();
        baseBean.setName("我是MyBean");
        baseBean.setOtherbean(otherbean);
        return baseBean;
    }

    @Bean
    public OtherBean OtherBean(){
        return new OtherBean();
    }

}

  1. 测试

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = ApplicationConfig05.class)

public class JavaConfigTest {

 

    @Autowired

    private BaseBean baseBean;

    @Autowired

    private OtherBean otherBean;

 

    @Test

    public void testMyBean() throws Exception{

        System.out.println("baseBean.name  "+baseBean.name);

        System.out.println("otherBean.name  "+otherBean.name);

        System.out.println(baseBean);

    }

}

  1. 总结

 

 

//定义MyBean的条件类,MyBean是否能定义,通过该类的  matches 方法返回的boolean决定的
public class MyBeanCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //环境对象
        Environment environment = context.getEnvironment();
        //操作系统名字
        String os = environment.getProperty("os.name");
        System.out.println(os);
        if(os.equals("Windows 10")){
            return true;
        }
        return false;
    }
}

 

六.条件Conditional

Conditional用来对某些组件是否注册做条件限制,比如:Conditional注解帖在bean的定义方法上来判断,如果不满足条件就不会定义bean

创建一个Bean,如果操作系统的环境是Windows ,那就创建,否则不创建

1.流程

1.建包
2.建类MyBean
3.建配置类

@Configuration
public class ApplicationConfig {

    @Bean
    @Conditional(value = MyBeanCondition.class)
    public MyBean myBean(){
        return new MyBean();
    }
}


4.配置条件类,配置MyBean

//定义MyBean的条件类,MyBean是否能定义,通过该类的  matches 方法返回的boolean决定的
public class MyBeanCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //环境对象
        Environment environment = context.getEnvironment();
        //操作系统名字
        String os = environment.getProperty("os.name");
        if(os.equals("Windows 10")){
            return true;
        }
        return false;
    }
}

  1. 测试

2.总结

1. @Conditional(value = MyBeanCondition.class)用来映射条件类的字节码文件

2. 条件类的本质是实现 Conditio接口的matches方法,该方法返回一个布尔值。

七.Import导入

@Import标签,可以有用来实现配置类之间的导入,如同 “<import resource="shriot.xml" /> 导入配置 , 当然还可以通过导入ImportSelector,以及导入ImportBeanDefinitionRegistrar的方式注册Bean。

1.导入配置Configuration

演示案例:创建两个配置类,一个配置类 ApplicationConfig 配置MyBean,另一个配置类 OtherConfig 配置OtherBean,使用@Improt把两个配置类导入在一起,并且MyBean中的OtherBean要有值

 

//主配置类
//@Import(OtherConfig.class): 导入另外一个配置类
@Configuration
@Import(OtherApplicationConfig.class)
public class BaseApplicationConfig {

    @Bean
    public MyBean myBean(OtherBean otherBean){
        MyBean myBean = new MyBean();
        myBean.setOtherBean(otherBean);
        return myBean;
    }
}

 

//第二个配置类
@Configuration
public class OtherConfig {
    @Bean
    public OtherBean otherBean(){
        return new OtherBean();
    }
}

 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfig.class)
public class JavaConfigTest {

    @Autowired
    private MyBean myBean;

    @Autowired
    private OtherBean otherBean;

    @Test
    public void testMyBean() throws Exception{
        System.out.println(myBean);
        System.out.println(myBean.getOtherBean());
        System.out.println(otherBean);
    }
}

2.总结

显然就是在 五.依赖注入的基础上吧把一个配置类的东西拆开放在两个配置类里面,扩展的类通过@Import(OtherApplicationConfig.class)链接基础配置类,同时测试文件导入基础配置类。

  1. 导入ImportSelector
  • SpringBoot-HelloWorld

1.HelloWorld

使用Spring创建有一个简单Web程序,通过浏览器访问 http://localhost:8080 能够返回“hello world”信息

    1. HelloWorld-web应用

打开官网https://docs.spring.io/spring-boot/docs/2.1.13.RELEASE/reference/html/getting-started-installing-spring-boot.html#getting-started-installation-instructions-for-java

1.配置pom.xml

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

2.创建配置类

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!Spring Boot";
    }

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

}

3.成功

2.SpringBoot的特点

1.使用注解配置,无需xml(简单粗暴)

2.快速搭建,开发

3.简化的maven

4.方便的和三方框架集成

5.内嵌tomcat,部署简单

6.内置健康检查,监控等

7.自动配置,让配置更加简单

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值