Spring的开发配置与Spring中bean的实例化

来源:互联网 发布:淘宝怎么给朋友发链接 编辑:程序博客网 时间:2024/06/15 10:31

Spring

1.   三种实例化bean的方法

1)    第一种是使用类构造器实例化;

<bean id="personService"class="com.lcq.service.impl.PersonServiceBean"></bean>


2)    第二种是使用静态工厂方法实例化;

      <beanid="personService1"class="com.lcq.service.impl.PersonServiceBeanFactory"factory-method="createPersonServiceBean"></bean>


3)    第三种是使用实例工厂方法实例化;

<bean id="PersonServiceBeanFactory"class="com.lcq.service.impl.PersonServiceBeanFactory"></bean><bean id="personService2" factory-bean="PersonServiceBeanFactory"factory-method="createPersonServiceBean2"></bean>


2.   bean的作用域,默认的情况之下,spring容器的bean的作用域是单实例的,也就是说当我们从容器中得到的bean实例是同一个。可以使用scope标签设置bean的作用域为原型,也就是说每次得到的bean是不同的对象实例。scope="prototype"。注意默认情况下的bean是在spring容器实例化的时候就进行实例化的;当是原型时bean的实例化是在getbean的时候进行实例化的。也可以在xml中配置bean的加载时机为延迟。

3.   spring的依赖注入之使用属性setter方法实现注入:ref标签或者使用内部bean

1)        

<bean id="personDao" class="com.lcq.dao.impl.PersonDaoBean"></bean>    <bean id="personService" class="com.lcq.service.impl.PersonServiceBean"     init-method="init"destroy-method="destory">        <property name="personDao" ref="personDao"></property>     </bean>


2)      

  <bean id="personService"class="com.lcq.service.impl.PersonServiceBean"     init-method="init"destroy-method="destory"><property name="personDao" >        <bean class="com.lcq.dao.impl.PersonDaoBean"/></ property>     </bean>

 

配置xml实现spring注入Set和Map等集合类型。

<property name="sets">        <set>            <value>第一个</value>            <value>第二个</value>            <value>第三个</value>        </set>        </property>               <property name="maps">        <map>                   <entry key="key1" value="value1"/>            <entry key="key2" value="value2"/>            <entry key="key3" value="value3"/>               </map>   </property>


4.   使用构造器实现注入

5.   使用注解进行注入

6.   使用注解将bean添加到spring的管理中。

在xml中配置:

<?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-2.5.xsd          http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">     <context:component-scan base-package="com.lcq"/></beans>


这样spring容器会在启动时将在指定的包的目录下进行查询查到所有相关的bean对其进行加载和注入。

在相应的需要加载的bean定义的前面添加注解进行标识。

//使用注解将bean添加到spring容器的管理中@Service @Scope("prototype")public class PersonDaoBean implements PersonDao {    //利用注解实现对象初始化操作    @PostConstruct    public void init(){       System.out.println("initinvoked");    }    public void add(){       System.out.println("add methodis invoked!");    } }