一、创建maven工程,导入坐标依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
二、编写demo,编写具体的实现方法
package com.qcby.service;
public class Demo {
public void hello() {
System.out.println("hello world");
}
}
三、在resources目录下创建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">
<!--IOC管理bean-->
<!--id:类的唯一标识符 class:类的全路径名-->
<!-- 相当于new了名为demo的Demo-->
<bean id="demo" class="com.qcby.service.Demo" />
</beans>
创建Spring项目没有Spring Config文件怎么办_何妨徐行的博客-CSDN博客
四、编写测试方法
Test包在java测试根下
package com.qcby.Test;
import com.qcby.service.Demo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DemoTest {
//传统写法
@Test
public void run(){
Demo demo =new Demo();
demo.hello();
}
// 把创建对象的权利交给spring
@Test
public void springdun(){
// 加载配置文件
ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取对象
Demo demo = (Demo) ac.getBean("demo");
demo.hello();
}
}
第一种写法是不用springioc的写法,需要我们自己new对象。
第二中我们在applicationContext.xml中<bean id="demo" class="com.qcby.service.Demo" />
相当于new了名为demo的Demo
接下来该学习如何使用注解和xml了