1.构建一个maven工程:
http://projects.spring.io/spring-framework/#quick-start
java
package com.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Day01 { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml"); HelloWorld obj = (HelloWorld) ctx.getBean("helloworld"); System.out.println(obj); } }
beans.xml在src/main/resource中间。
beans.xml的头可以参照
http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framewor…
其中http://docs.spring.io/spring/docs/
列举出了所有的版本的reference
beans.xml:
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.xsd"> <bean id="helloworld" class="com.spring.HelloWorld"> <property name="age" value="12"></property> <property name="name" value="tango"></property> </bean> </beans>
在<property>
中间,name应该指的是方法名,而不是属性名,因为反射是根据方法名来注入的。
还有一种注入方式,就是可以将字面值写到<value>
标签中:
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.xsd"> <bean id="helloworld" class="com.spring.HelloWorld"> <property name="age"> <value>12</value> </property> <property name="name"> <value>tango</value> </property> </bean> </beans>