4. Container function


[Shang Silicon Valley] SpringBoot2 Zero-Basic Introductory Tutorial - Lecturer: Lei Fengyang
Notes

The road is still going on, the dream is still waiting

1. Add components

1.1、@Configuration

  • Basic use: the current class is a configuration class
  • Full mode and Lite mode
    • example
    • best practice
    • There is no dependency between configuration class components Use Lite mode to speed up the container startup process and reduce judgment
    • There is a dependency between the configuration class components, and the method will be called to get the previous single instance component, using the Full mode

1. Configuration example

//#############################Configuration使用示例#############################
/**
 * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
 * 2、配置类本身也是组件(被spring的cgli增强了的对象)
 * 3、proxyBeanMethods:代理bean的方法(spring boot2 新增proxyBeanMethods 属性)
 *      Full(proxyBeanMethods = true 默认)、【配置类是代理对象,保证每个@Bean方法被调用多少次返回的组件都是单实例的】
 *      Lite(proxyBeanMethods = false)【配置类不是代理对象,每个@Bean方法被调用多少次返回的组件都是新创建的】
 *      组件依赖必须使用Full模式默认。
 *      其他默认是否Lite模式
 */
 
//告诉SpringBoot这是一个配置类 == 配置文件
@Configuration(proxyBeanMethods = true)
public class MyConfig {
    
    

    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次,获取的都是之前注册容器中的单实例对象
     * @return
     */
    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    public User user01(){
    
    
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件(条件:配置类 proxyBeanMethods = true)
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom") //自定义组件名字
    public Pet tomcatPet(){
    
    
        return new Pet("tomcat");
    }
}

2. Test code

//#############################@Configuration测试代码如下#############################
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {
    
    

    public static void main(String[] args) {
    
    
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2、查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
    
    
            System.out.println(name);
        }

        //3、从容器中获取组件,默认就是单例
        Pet tom01 = run.getBean("tom", Pet.class);
        Pet tom02 = run.getBean("tom", Pet.class);
        // true
        System.out.println("组件:"+(tom01 == tom02));

        //4、验证配置类本身也是一个组件(被代理的组件),获取配置类
        MyConfig bean = run.getBean(MyConfig.class);
        //可以打印:com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
        System.out.println(bean);

        // 5、验证获取组件对象,调用组件方法,返回对象是否为单例
        //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。
        //SpringBoot会检查这个组件是否在容器中有。
        //有就保持组件单实例
        User user = bean.user01();
        User user1 = bean.user01();
        //true,证明是从容器中取是单例。
        System.out.println(user == user1);

        //6、验证user01中的tom组件与容器中的tom组件是否相同
        //验证组件依赖(条件:配置类 proxyBeanMethods = true)
        User user01 = run.getBean("user01", User.class);
        Pet tom = run.getBean("tom", Pet.class);
        // 结果:相同
        System.out.println("用户的宠物:"+(user01.getPet() == tom));
    }
}

1.2、@Bean、@Component、@Controller、@Service、@Repository

You can use @Bean to register some third-party jar packages, because you cannot write @Component, @Controller, @Service, @Repository annotations on jar classes.

Annotating @Component, @Controller, @Service, @Repository on a custom class can inject components into the container.

1.3、@ComponentScan、@Import

@ComponentScan: Specify the package scanning location and specify the package scanning rules.

@Import: Written in the class, import the specified component into the container, there can be more than one, and it can be used freely in any class.

/** 4、@Import({User.class, DBHelper.class})
 * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
 */

@Import({
    
    User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
    
    
}

Advanced usage of @Import

1.4、@Conditional

spring annotations. condition

Conditional assembly: If the conditions specified by Conditional are met, component injection is performed

insert image description here

configuration class

//=====================测试条件装配==========================
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom") 当容器中有tom这个组件,当前配置类才生效
public class MyConfig {
    
    

    @ConditionalOnBean(name = "tom") //当容器中有tom这个组件的时候,在向容器中添加user01组件
    @Bean
    public User user01(){
    
    
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    //@Bean("tom")
    public Pet tomcatPet(){
    
    
        return new Pet("tomcat");
    }
}

main program

public static void main(String[] args) {
    
    
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2、查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
    
    
            System.out.println(name);
        }

        // 3、判断容器中是否包含tom组件
        boolean tom = run.containsBean("tom");
        System.out.println("容器中Tom组件:"+tom);
        // 4、判断容器中是否包含user01组件
        boolean user01 = run.containsBean("user01");
        System.out.println("容器中user01组件:"+user01);
        // 5、判断容器中是否包含tom22组件
        boolean tom22 = run.containsBean("tom22");
        System.out.println("容器中tom22组件:"+tom22);


}

2. Introduction of native configuration files

2.1、@ImportResource

Write once on any configuration class, you can import the spring xml configuration file, which is mainly used to import the configuration file of the spring project.

1. spring beans.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="haha" class="com.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>

2. Configuration class

@Configuration
@ImportResource("classpath:beans.xml")
public class MyConfig {
    
    }

3. Main program

@SpringBootApplication // 标注一个主程序,说明是SpringBoot应用
public class HelloWorldMainApplication {
    
    
    public static void main(String[] args) {
    
    
        // Spring应用启动起来
        SpringApplication.run(HelloWorldMainApplication.class, args);
        
        //======================测试=================
        boolean haha = run.containsBean("haha");
        boolean hehe = run.containsBean("hehe");
        System.out.println("haha:"+haha); //true
        System.out.println("hehe:"+hehe); //true
    }
}

3. Configuration binding

Use Java to read the content in the properties file, and encapsulate it into a JavaBean for ready use.

3.1. Use native Java

public class getProperties {
    
    
     public static void main(String[] args) throws FileNotFoundException, IOException {
    
    
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
    
    
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }

3.2、@ConfigurationProperties

Bind the content of the configuration file to the properties in the component

3.3、@EnableConfigurationProperties + @ConfigurationProperties

In this way, you must write @EnableConfigurationProperties(Car.class) in the configuration class (Car.class enables the property configuration function)

The usage scenario is a third-party jar package, and @Component cannot be added to the class, and there are @ConfigurationProperties annotations on the class

1. Configuration class

@Configuration
@EnableConfigurationProperties(Car.class)
// 1、开启Car配置绑定功能,开启了@ConfigurationProperties注解才能有效
// 2、把这个Car组件自动注册到容器中
public class MyConfig {
    
    
}

2、properties

mycar.brand=YD
mycar.price=90000

3. Entity class

/**
 * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
 * prefix:前缀,绑定配置文件内前缀myvar.名称的值
 */
@ConfigurationProperties(prefix = "mycar")
public class Car {
    
    

    private String brand;
    private Integer price;
    // 有参、无参
    // set、get
    // toString
}

4、controller

@Controller
public class HelloController {
    
    

    private Car car;

    @Autowired
    public void setCar(Car car) {
    
    
        this.car = car;
    }

    @ResponseBody
    @RequestMapping("/car")
    public Car getCar(){
    
    
        return this.car;
    }
}

3.4、@Component + @ConfigurationProperties

1、properties

mycar.brand=YD
mycar.price=90000

2. Entity class

@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    
    
    private String brand;
    private Integer price;

// set/get方法
// toString方法
}

3、controller

@Controller
public class HelloController {
    
    

    private Car car;

    @Autowired
    public void setCar(Car car) {
    
    
        this.car = car;
    }

    @ResponseBody
    @RequestMapping("/car")
    public Car getCar(){
    
    
        return this.car;
    }
}

Guess you like

Origin blog.csdn.net/zhao854116434/article/details/129928348