您的位置:首页 > 编程语言 > Java开发

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

2017-09-05 09:43 399 查看
(一)在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)
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: