引入依赖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