1、新建一个java工程
2、添加spring相关的jar包并添加到引用

3、添加spring依赖的相关jar包并添加到引用

4、编写spring配置文件applicationcontext.xml
新建applicationContext.xml文件,然后编写头文件。关于spring头文件的写法可以参考spring提供的guide。
解压下载的spring文件,找到docs\spring-framework-reference\html\index.html并打开,然后找到

在打开的页面中会有头文件的相关写法

如下是编写的applicationContext.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="user" class="domain.User"> <property name="name" value="fei"/> </bean> </beans>
5、编写测试程序运行spring
一、编写一个测试的实体类User
public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public User(String name) { this.name = name; } public User() { } public void sayName(){ System.out.println(name); } }
二、编写测试文件
方式一:使用Spring测试框架
@RunWith(SpringJUnit4ClassRunner.class)//使用spring的测试框架 @ContextConfiguration("classpath:applicationContext.xml")//加载spring配置文件 ,加载放在其他文件夹中的配置文件:/config/applicationContext.xml public class SpringTest { @Autowired private User user; @Test public void test1(){ user.sayName(); } }
方式二:通过classpathxmlapplicationcontext加载spring配置文件来实现ApplicationContext
public class SpringTest02 { private static ApplicationContext ctx; static { ctx = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml"); } @Test public void test1() { ctx.getBean("user",User.class).sayName(); } }