Spring中Bean的实例化方式

文章目录

  • Spring中的bean的实例化方式
    • 一、基于XML配置
      • 1. 无参构造方法实例化对象
      • 2. 静态工厂类实例化对象
      • 3. 普通工厂实例化对象
    • 二、基于注解方式装配Bean(自动装配)
    • 三、通过Java代码装配Bean(组件扫描)

Spring中的bean的实例化方式

一、基于XML配置

bean基于配置实例化的方式有三种实现

  • 通过无参构造实例化
  • 通过静态工厂方法实例化
  • 通过普通工厂实例化

1. 无参构造方法实例化对象


<bean id="student" class="com.wyscoder.spring.IOC.pojo.Student"/>

注:如果不指定构造函数,会生成一个默认的无参构造函数

如果显性的指定有参构造函数,不会生成默认的构造函数,必须在显性指定一个无参构造函数,否则实例化对象会抛出异常

2. 静态工厂类实例化对象

首先,使用一个工厂的静态方法返回对象

public class StaticBeanFactory {
    public static Student getBean() {
        return new Student();
}

在配置文件中使用工厂的静态方法返回对象

通过静态工厂实例化bean
class:指定工厂类的路径
factory-method:在工厂类中获取对象的方法

<bean id="student2" class="com.wyscoder.spring.IOC.StaticBeanFactory" factory-method="getBean"/>

测试
Spring中Bean的实例化方式_第1张图片

3. 普通工厂实例化对象

通过工厂创建一个非静态方法得到对象

public class CommonBeanFactory {
    public Student getBean() {
        return new Student();
    }
}

配置文件中是同工厂的非静态方法返回对象

第一步: 创建工厂实例
第二步: 指定工厂和工厂方法

	
    <bean id="beanFactory" class="com.wyscoder.spring.IOC.CommonBeanFactory"/>
    
    <bean id="student3" class="com.wyscoder.spring.IOC.pojo.Student" factory-bean="beanFactory" factory-method="getBean"/>

测试
Spring中Bean的实例化方式_第2张图片

二、基于注解方式装配Bean(自动装配)

通过component注解标记类

类似于xml配置文件 @Component类似于xml中的bean标签 value值类似于id属性。
Spring中Bean的实例化方式_第3张图片

配置启动组件扫描



<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 http://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:component-scan base-package="com.wyscoder.spring.IOC"/>
beans>

使用component-scan标签方式来扫描包路径及子类路径
第一步必须引入context约束,否则无法出现context标签

在Spring中主要提供了四个注解来标注bean

  • @Component 通用的标注形式
  • @Repository 对Dao实例类进行标注
  • @Service 对Service层类进行标注
  • @Controller 对Controller层类进行标注

测试
Spring中Bean的实例化方式_第4张图片

三、通过Java代码装配Bean(组件扫描)

给定一个配置类,在配置类上添加@Configuration注解,@Configuration注解表明当前类是一个配置类,告诉Spring应用上下文如何创建bean细节。

@Configuration
public class TestConfig {
    
}

将交给spring管理的类声明为bean,编写一个方法,方法会创建所需要的bean的实例,给方法添加上@Bean注解。@Bean注解会告诉Spring这个方法会返回一个对象,这个对象会被注册到spring中。

@Configuration
public class TestConfig {
    @Bean(name = "student2")
    public Student student() {
        return new Student();
    }
}

测试
Spring中Bean的实例化方式_第5张图片

你可能感兴趣的:(Java,spring,java,spring,IOC)