Java Spring資料單元配置過程解析
阿新 • • 發佈:2020-12-14
基本原理 - 容器和bean
在Spring中,那些組成你應用程式的主體(backbone)及由Spring IoC容器所管理的物件,被稱之為bean。 簡單地講,bean就是由Spring容器初始化、裝配及管理的物件,除此之外,bean就與應用程式中的其他物件沒有什麼區別了。
也就是說,其實spring 就是在載入配置檔案beans.xml的時候,通過反射機制,去例項化<bean>標籤裡面的類的過程。這裡可以通過在類的預設無參構造方法中寫點東西判斷出來。
1. 配置元資料
基於XML的配置元資料的基本結構:beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- 更多的bean的時候 在引用的xml檔案一定是要帶spring dtd頭的檔案--> <import resource="services.xml"/> </beans>
services.xml
在配置檔案裡面命名其實id 和name都是一樣的
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="userService" name="userService" class="com.sun.service.UserService"> <property name="name"> <value>sunxin</value> </property> </bean> </beans>
2. 例項化容器
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"beans.xml"});
3. bean的別名
<!--name指向的是已經存在該id的bean,alias是給給該bean命的別名-->
<alias name="userService" alias="user"/>
呼叫可以通過:
UserService us = (UserService) app.getBean("user");
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。