【Spring框架】IOC中创建bean和dependencies的几种方式

IOC容器

IOC容器与原始相比

原始工程中,controller调用server,server调用mapper,每一层与下一层关联,当变更其中一层时,其他层均需要适应性修改,耦合性过高。

添加IOC容器后,全部交给IOC容器管理,通过注入类、对象,将可能用到的作为bean交给IOC管理,每一层独立开来,极大降低耦合性。

1.使用容器

启动类中通过加载xml文件创建ApplicationContext对象,在上下文对象中获取Bean对象(可通过第二参数定义Bean对象中存储的数据类型),调用方法。

public class ApplicationContext{
    // create and configure beans
    ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

    // retrieve configured instance
    PetStoreService service = context.getBean("petStore", PetStoreService.class);

    // use configured instance
    List<String> userList = service.getUsernameList();
}

提前编写好xml文件,头文件复制粘贴即可,标签属性有id和class,可通过嵌套形式将属性和类存放在bean中,方式有set注入,构造器注入,依赖注入,命名空间注入。

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountDao"
        class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for data access objects go here -->

</beans>

1.1.创建bean

创建bean的方式有三种,分别是构造函数实例化,静态工程实例化,实例工厂实例化。
#####1.1.1构造函数实例化,默认是使用空参构造,若没有空参构造,必报错。

<beans>
    <bean id="exampleBean" class="examples.ExampleBean"/>
    <bean name="anotherExample" class="examples.ExampleBeanTwo"/>
</beans>
1.1.2静态工厂方法进行实例化。

在定义使用静态工厂方法创建的 bean 时,使用class 属性指定包含static工厂方法的类,使用命名属性factory-method指定工厂方法本身的名称

<bean id="clientService"
      class="examples.ClientService"
      factory-method="createInstance"/>

与之配合的类

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}
1.1.3使用实例工厂方法进行实例化

从容器中调用现有 bean 的非静态方法来创建新 bean。
要使用此机制,请将class属性留空,并在factory-bean属性中指定当前(或父级或祖先)容器中的 bean 的名称,该容器包含要调用以创建对象的实例方法。 factory-method使用属性设置工厂方法本身的名称。

<beans>
    <!-- the factory bean, which contains a method called createInstance() -->
    <bean id="serviceLocator" class="examples.DefaultServiceLocator">
        <!-- inject any dependencies required by this locator bean -->
    </bean>

    <!-- the bean to be created via the factory bean -->
    <bean id="clientService"
          factory-bean="serviceLocator"
          factory-method="createClientServiceInstance" />
</beans>

与之匹配的类

public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

1.2.依赖项注入

注入类中对应属性的方式有set注入、构造器注入

1.2.1set注入
<bean id="exampleBean" class="examples.ExampleBean">
    <!-- setter injection using the nested ref element -->
    <property name="beanOne">
        <ref bean="anotherExampleBean"/>
    </property>

    <!-- setter injection using the neater ref attribute -->
    <property name="beanTwo" ref="yetAnotherBean"/>
    <property name="integerProperty" value="1"/>
</bean>
1.2.2构造器注入
<beans>
    <!-- 参数解析 -->
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg ref="beanTwo"/>
        <constructor-arg ref="beanThree"/>
    </bean>
    <bean id="beanTwo" class="x.y.ThingTwo"/>
    <bean id="beanThree" class="x.y.ThingThree"/>
    
    <!--参数类型匹配--> 
    <bean id="exampleBean" class="examples.ExampleBean">
        <constructor-arg type="int" value="7500000"/>
        <constructor-arg type="java.lang.String" value="42"/>
    </bean>
    
    <!-- 参数索引 -->
    <bean id="exampleBean" class="examples.ExampleBean">
        <constructor-arg index="0" value="7500000"/>
        <constructor-arg index="1" value="42"/>
    </bean>
    
</beans>
1.2.3延迟初始化的 Bean

默认情况下,作为初始化过程的一部分,ApplicationContext实现会快速地创建和配置所有单例bean。

延迟初始化的 bean 告诉 IoC 容器在第一次被请求时创建一个 bean 实例,而不是在启动时。

添加属性lazy-init

<beans>
    <bean id="lazy" class="com.something.ExpensiveToCreateBean" lazy-init="true"/>
    <bean name="not.lazy" class="com.something.AnotherBean"/>
</beans>

与之对应的是在容器级别初始化,即创建Application时创建bean实例 default-lazy-init属性

<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>
1.2.4自动装配

autowire属性为 bean 定义指定自动装配模式,可为属性添加一下值。
在这里插入图片描述

常用注解

@Autowrite:先通过类型匹配,再通过名称匹配
@Autowrite不能唯一通过注解绑定时,可配合@Qualifier(value="xxx)配合使用
@Nullable:标记的字段允许为null
@Resource(value="xxx):先通过名称匹配,再通过类型匹配,用属性value可指定bean名称

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值