spring ioc(bean)

1.首先講IOC bean的加載   

1.1懶加載(延時加載)beanFactory(單例模式)

  @Test
    public  void  createbean(){
       //加載spring.xml配置文件
        BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("spring.xml"));
      //獲取users  bean對象
        user user=(user) beanFactory.getBean("users");
      //輸出
        System.out.println(user);System.out.println(user);
    }

1.2及時加載ClassPathXmlApplicationContext 

 public void demo() throws Exception {
//加載spring.xml文件
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//得到bean對象
        user user=(user)applicationContext.getBean("users");
//輸出
        System.out.println(user);

    }

2bean的常用屬性

id :用於getbean()方法  id不能爲特殊字符 ;

class:創建對象所在類的路徑;

name:功能和屬性id差不多,可以是特殊字符;

scope:作用域

singleton:默認 在每一個springioc容器中定義對應一個對象實例;

prototype:一個bean對應多個對象實例;

request:在一次HTTP請求中,一個bean對應一個對象實例,每次都會有各自的bean實例,他們根據某個bean定義創建而成,只在web的spring ApplicationContext下有效;

session:在一個HTTP sesion中,一個bean定義一個實例,只在web的spring ApplicationContext下有效;

global-session:global session作用域類似於標準的HTTP Session作用域,不過它僅僅在基於portlet的web應用中才有意義。Portlet規範定義了全局Session的概念,它被所有構成某個portlet web應用的各種不同的portlet所共享。在global session作用域中定義的bean被限定於全局portlet Session的生命週期範圍內。
 

spring.xml

<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-4.3.xsd>
<!--創建一個uers的bean-->
    <bean id="users"   class="com.zx.pojo.user" scope="prototype"></bean







</beans>




3注入

1.value直接賦值

  <!--<bean id="users"   class="pojo.user" scope="prototype">-->
        <!--<property name="uid" value="1"></property>-->
        <!--<property name="uname" value="2"></property>-->
        <!--<property name="upwd" value="3"></property>-->
    <!--</bean>-->

2.集合注入

list


    <!--<bean id="lists" class="pojo.lists">-->
       <!--<property name="lists">-->
           <!--<list>-->
           <!--<ref bean="users"></ref>-->
           <!--<ref bean="users2"></ref>-->
           <!--</list>-->
       <!--</property>-->
    <!--</bean>-->

map

 <!--<bean id="map" class="pojo.map" scope="prototype">-->
     <!--<property name="usermap" >-->
         <!--<map>-->
             <!--<entry key="1" value-ref="users"></entry>-->
             <!--<entry key="2" value-ref="users2"></entry>-->
         <!--</map>-->
     <!--</property>-->
  <!--</bean>-->

構造方法注入:(constructor-arg)

 <bean id="users" class="pojo.user">
      <constructor-arg index="0" value="123456"></constructor-arg>
        <constructor-arg index="1" value="密碼"></constructor-arg>
        <constructor-arg index="2" value="aaaaa"></constructor-arg>
    </bean>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章