创建Java工程,导入坐标依赖
<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>
编写接口和实现类,编写具体的实现方法
packagecom.qcbyjy.service;
public interface UserService{
public void hello();
}
package com.qcbyjy.service;
public class UserServiceImpl implements UserService{
@Override
public void hello(){
System.out.println("HelloIOC!!");
}
}
编写Spring核心的配置文件,在src目录下创建applicationContext.xml的配置 文件,名称是可以任意的,但是一般都会使用默认名称。
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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-->
<beanid="userService"class="com.qcbyjy.service.UserServiceImpl"/>
</beans>
把log4j.properties的配置文件拷贝到resources目录下,做为log4j的日志配置 文件。
编写测试方法。
package com.qcbyjy.test;
import com.qcbyjy.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo1{
/**
*入门程序
*/
@Test
public void run1(){
//使用Spring的工厂
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//通过工厂获得类:
UserService userService=(UserService) applicationContext.getBean("userService");
userService.hello();
}
}
ApplicationContext接口,工厂的接口,使用该接口可以获取到具体的Bean对 象。该接口下有两个具体的实现类。springCould配置中心
ClassPathXmlApplicationContext,加载类路径下的Spring配置文件。 FileSystemXmlApplicationContext,加载本地磁盘下的Spring配置文件。