SpringBoot


第一章


  1. 为什么要使用SpringBoot

    因为Spring,SpringMVC需要使用的大量的配置文件(xml文件)

    还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象

    需要了解其他框架配置规则。

  2. SpringBoot就相当于不需要配置文件的Spring+SpringMVC。常用的框架和第三方库都已经配置好了。

    拿来就可以使用 了。

  3. SpringBoot开发效率高,使用方便多了。

1.1什么是JavaConfig


JavaConfig:是Spring提供的试音Java类配置容器。配置SpringIOC容器的纯Java方法。在这个Java类这可以创建Java对象,把对象放入Spring容器中(注入到容器)

优点:

可以使用面向对象的方式,一个配置类可以继承配置类,可以重写方法避免繁琐的xml配置

使用两个注解:

  1. @Configuration:放在一个类的上面,表示这个类是作为配置文件使用的。
  2. @Bean:申明对象,把对象注入到容器中

MyTest.java

package com.study.config;

import com.study.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration:表示当前类是作为配置文件使用的。就是用来配置容器的
 * 位置:在类的上面
 * SpringConfig这个类相当于beans.xml
 */
@Configuration
public class SpringConfig {

    /**
     * 创建方法,方法的返回值是对象。在方法的上面加入@Bean
     * 方法的返回值独享就注入到容器中
     * @Bean:把独享注入到Spring容器中。作用相当于<bean>
     *     位置:方法的上面
     *
     *     说明:@Bean,不指定对象的名称,默认是方法名是  id
     */
    @Bean
    public Student createStudent(){
        Student s1 = new Student();
        s1.setName("张三");
        s1.setAge(26);
        s1.setSex("男");
        return s1;
    }

    /**
     * 指定对象在容器中的名称(指定<bean></bean>的id属性)
     * @Bean的name属性,指定对象的名称(id)
     */
    @Bean(name = "lisiStudent")
    public Student makeStudent(){
        Student s1 = new Student();
        s1.setName("李四");
        s1.setAge(22);
        s1.setSex("男");
        return s1;
    }

}

README.md

SpringConfig.java

package com.study.config;

import com.study.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration:表示当前类是作为配置文件使用的。就是用来配置容器的
 * 位置:在类的上面
 * SpringConfig这个类相当于beans.xml
 */
@Configuration
public class SpringConfig {

    /**
     * 创建方法,方法的返回值是对象。在方法的上面加入@Bean
     * 方法的返回值独享就注入到容器中
     * @Bean:把独享注入到Spring容器中。作用相当于<bean>
     *     位置:方法的上面
     *
     *     说明:@Bean,不指定对象的名称,默认是方法名是  id
     */
    @Bean
    public Student createStudent(){
        Student s1 = new Student();
        s1.setName("张三");
        s1.setAge(26);
        s1.setSex("男");
        return s1;
    }

    /**
     * 指定对象在容器中的名称(指定<bean></bean>的id属性)
     * @Bean的name属性,指定对象的名称(id)
     */
    @Bean(name = "lisiStudent")
    public Student makeStudent(){
        Student s1 = new Student();
        s1.setName("李四");
        s1.setAge(22);
        s1.setSex("男");
        return s1;
    }

}

1.2@ImporResource


@ImportResource作用导入其他的xml配置文件,等于在xml

<import resources="其他配置文件"/>