IDEA2019; maven工程;
目录结构:
1.添加依赖;
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
</dependencies>
2.src下建包com.dao;
包中创建接口 TestDao; 接口中定义方法 sayHello;
package com.dao;
public interface TestDao {
//接口中定义方法
public void sayHello();
}
3.创建接口TestDao的实现类 TestDaoImpl ;
package com.dao;
public class TestDaoImpI implements TestDao {
//接口实现类
public void sayHello() {
System.out.println("Hello Spring ");
}
}
4.在resources下创建配置文件 applicationContext.xml;
并在文件中实现类 TestDaoImpl 创建一个id为 test 的 Bean;
<?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">
<!-- 将指定类TestDaoImpl配置给Spring,让spring创建其实例-->
<bean id="test" class="com.dao.TestDaoImpI" />
</beans>
5. 创建测试类;
package com.test;
import com.dao.TestDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//初始化Spring容器ApplicationContext,加载配置文件
ApplicationContext appCon = new ClassPathXmlApplicationContext
("applicationContext.xml");
//通过容器获取test实例
//test为配置文件中的id
TestDao tt = (TestDao)appCon.getBean("test");
tt.sayHello();
}
}
6. 执行main方法;
上述方法并没有使用new 创建 TestDaoImpl 的对象,而是通过Spring 容器来获取实现类的对象;
这就是Spring IoC工作机制。