spring的helloworld
步骤:
1.新建一个java工程,选中项目的名字右击,新建一个lib文件夹,用来存放spring的jar包
2.加入jar包:
3.在src下新建一个beans.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"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置一个 bean,其实相当于创建HelloWorld 的实例,并为该类的name属性赋值为spring-->
<bean id="helloWorld" class="com.xjj.spring.helloworld.HelloWorld">
<!-- 为属性赋值 -->
<property name="name" value="spring"></property>
</bean>
</beans>
4.在src下新建一个包取名为com.xjj.spring.helloworld,然后新建一个类Helloworld
public class HelloWorld {
public String name;
public void setName(String name) {
this.name = name;
}
public void hello(){
System.out.println("hello:"+name);
}
}
5.创建一个测试类:TestHelloWorld,需要注意的是beans.xml是你在src创建的spring的配置文件名,helloworld是beans.xml里面bean的id;
public class TestHelloWorld {
public static void main(String[] args) {
//1.创建spring的IOC容器
ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
//2.获取IOC容器Bean实例
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
//3.调用方法
helloWorld.hello();
}
}
public static void main(String[] args) {
//1.创建spring的IOC容器
ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
//2.获取IOC容器Bean实例
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
//3.调用方法
helloWorld.hello();
}
}
6.(Run as java Application)运行结果:出现如下结果,说明spring的helloworld创建成功
7.项目总体结构图: