Spring--->配置-DI---依賴注入
阿新 • • 發佈:2020-09-11
1、別名
-
id:bean的唯一識別符號,也就是相當於物件名
-
class:bean 物件的全限定名(包名加型別)
-
name:也是別名,而且更高階
<alias name="hello" alias="hello2"></alias>
2、Bean的配置
<bean id="hello" class="com.xian.pojo.Hello" name="hello3,ffff">
<constructor-arg index="0" value="Spring,Hello"></constructor-arg>
</bean>
3、import
合作開發時使用,匯入不同人的Bean
<import resource="beans.xml"/> <import resource="beans1.xml"/> <import resource="beans2.xml"/>
4、依賴注入
依賴:
set注入
<bean id="student" class="com.xian.Dao.Student"> <property name="name" value="xian"/> <property name="address" ref="address"/> <property name="books"> <array> <value>java se</value> <value>java ee</value> <value>java web</value> <value>java Spring</value> </array> </property> <property name="hobbys"> <list> <value>敲程式碼</value> <value>敲臉盆</value> <value>敲鐘</value> </list> </property> <property name="card"> <map> <entry key="1" value="14141414141"/> <entry key="2" value="22222222222"/> </map> </property> <property name="games"> <value>LOL</value> </property> <property name="wife"> <null></null> </property> <property name="info"> <props> <prop key="url">www.baidu.com</prop> <prop key="name">baidu</prop> </props> </property> </bean>
P名稱空間和C名稱空間
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" <bean id="hello" class="com.xian.pojo.Hello" p:str="hello P:名稱空間"></bean> <bean id="helloc" class="com.xian.pojo.Hello" c:str="hello C:名稱空間"></bean> public void test() { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Hello hello = context.getBean("hello",Hello.class); System.out.println(hello.toString()); Hello helloc = context.getBean("helloc",Hello.class); System.out.println(helloc.toString()); }
5、bean的作用域
1.單例模式(Spring預設機制)
<bean id="hello" class="com.xian.pojo.Hello" p:str="hello P:名稱空間"
scope="singleton"> </bean>
2.原型模式:每次Get都會產生一個新物件
<bean id="helloc" class="com.xian.pojo.Hello" c:str="hello C:名稱空間"
scope="prototype"></bean>
其餘的request、sessioon、application都只作用於web開發中