Spring之autowire(自动装配)与lazy-init

(一)在Spring的配置文件中可以通过autowire属性来实现自动装配,就不需要设置  setter方法:<property name="daoId" value="2"></property>

autowire属性的常用取值:byName , byType ,default 。  

(二)autowire属性可以写在bean标签或者beans标签 

在beans标签 设置:default-autowire=“byType” 所有的bean都不要配置注入了。各个bean通过设置autowire=“default”,表示使用beans标签的default-autowire设置的注入方式。

实例:

<?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-2.5.xsd"
         default-autowire="byType" >
   
  <bean name="userDAO2" class="com.bjsxt.dao.impl.UserDAOImpl">
  <property name="daoId" value="2"></property>
  </bean>

  <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byType">
  </bean>
</beans>

(三)一些bean可以设置lazy-init="true"即:用到它时在初始化。可以提高运行效率。

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
<bean name="not.lazy" class="com.foo.AnotherBean"/>
也可以设置所有bean都懒加载:在beans标签内设置:

<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>


(四)init-method属性与destroy-Method属性:表示bean在初始化之前首先调用init-method属性指定的方法,容器关闭的时候会首先调用destroy-method属性指定的方法。

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {

    public void init() {
        // do some initialization work
    }

}
通过实现   org.springframework.beans.factory.InitializingBean 接口也可以实现上述功能

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {

    public void afterPropertiesSet() {
        // do some initialization work
    }

}

对于destroy-method属性实例:

<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {

    public void cleanup() {
        // do some destruction work (like releasing pooled connections)
    }

}

通过实现org.springframework.beans.factory.DisposableBean 接口也能实现容器在销毁时调用destroy方法。

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {

    public void destroy() {
        // do some destruction work (like releasing pooled connections)
    }

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一位远方的诗人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值