1.首先把spring框架所依赖的jar包下好。
2.build path 导入jar包,右键项目,build path–》add External Archives --》你下载好jar包所存放的位置
写一个HelloWorld 类
package com.beans;
public class HelloWorld {
private String name;
// 这里的set方法对应bean中的propert name
public void setName2(String name) {
this.name = name;
}
public void hello() {
System.out.println(\"hello:\"+name);
}
}
写一个主类,开始的时候没用spring,直接主类调用setName赋值,后来用xml文件的setter注入的方式赋值。
package com.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建一个HelloWorld 的对象
//HelloWorld helloWorld=new HelloWorld();
// 为name属性赋值
//helloWorld.setName(\"xiongtong\");
//1.创建spring的IOC容器对象
ApplicationContext ctx=new ClassPathXmlApplicationContext(\"applicationContext.xml\");
//2.从IOC容器中获取bean实例
HelloWorld helloWorld=(HelloWorld)ctx.getBean(\"helloWorld\");
//3.调用hello方法
helloWorld.hello();
}
}
这是.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 -->
<bean id=\"helloWorld\" class=\"com.beans.HelloWorld\">
<property name=\"name2\" value=\"spring\"></property>
</bean>
</beans>
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。





