引入依賴git
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.8.RELEASE</version> </dependency>
建立Hello類github
public class Hello { public void hello() { System.out.println("hello spring"); } }
編寫配置文件web
<?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.xsd"> <bean id="hello" class="cn.ann.Hello"/> </beans>
編寫測試類測試spring
@Test public void demo01() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Hello hello = (Hello) ac.getBean("hello"); hello.hello(); }
運行結果:
編程
new ClassPathXmlApplicationContext(配置文件路徑)
是對IOC容器初始化, 其返回值能夠用ApplicationContext或BeanFactory接收
ac.getBean("hello")
能夠獲取IOC容器中的指定對象, 參數能夠是id值, 也能夠是Class對象
<bean id="user" class="cn.ann.User"/>
使用普通工廠的方法建立session
<bean id="userFactory" class="cn.ann.UserFactory"/> <bean id="user" factory-bean="userFactory" factory-method="getUser"/>
<bean id="user" class="cn.ann.StaticFactory" factory-method="getUser"/>
使用構造函數注入app
<bean id="user" class="cn.ann.User"> <constructor-arg name="" value="" type="" index=""></constructor-arg> </bean>
使用set注入(更經常使用)框架
<bean id="user" class="cn.ann.User"> <property name="name" value="zs"/> <property name="age" value="23"/> <property name="birthday" ref="date"/> </bean>
bean屬性(省略了getter,setter和toString):函數
public class CollectionDemo { private String[] strings; private List<String> list; private Set<String> set; private Map<String, String> map; private Properties prop; }
array類型(String[])測試
<property name="strings"> <array> <value>aaa</value> <value>bbb</value> <value>ccc</value> </array> </property>
List類型
<property name="list"> <list> <value>AAA</value> <value>BBB</value> <value>CCC</value> </list> </property>
Set類型
<property name="set"> <set> <value>111</value> <value>222</value> <value>333</value> </set> </property>
Map類型
<property name="map"> <map> <entry key="key01" value="val01"/> <entry key="key02" value="val02"/> <entry key="key03" value="val03"/> </map> </property>
Properties類型
<property name="prop"> <props> <prop key="prop01">val01</prop> <prop key="prop02">val02</prop> <prop key="prop03">val03</prop> </props> </property>
注意: array, list和set均可以對list結構進行注入; entry和props均可以對Map結構進行注入
代碼連接: 此處 的 spring01-quickStart