1.导入 需要的JAR包
spring-beans.4.0.0.RELEASE.jar
spring-context-4.0.0
spring-core-4.0.0
spring-expression-4.0.0
commons-logging-1.1.3.jar
2.编写BEANS文件
这个配置文件的配置,可以从官方网站的spring-framework-reference 中的4.2.1小节中的 Configuration metadata中The following example shows the basic structure of XML-based configuration metadata:参考。
<?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.Helloworld"> <property name="username" value="zhangsan"></property> </bean> <!-- <bean id="..." class="..."> collaborators and configuration for this bean go here </bean> more bean definitions go here --> </beans>
3.编写 helloworld 类
package com.spring.helloworld; public class Helloworld { private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public void hello() { System.out.println("Hello:" + username); } }
4.编写MAIN方法
package com.spring.main; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.helloworld.Helloworld; public class TestSpring { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); Helloworld helloWorld = (Helloworld) ctx.getBean("helloworld"); helloWorld.hello(); } }
SPRING框架
1.属性的值,注入到SPRING容器中
2.实例不需要NEW出来,从容器中取得实例对象,再通过实例调用相应的方法。
运行结果:hello:zhangsan