1、创建项目
点击“Create New Project”,新建项目
选择Maven项目
项目配置
使用本地安装的Maven
一直点击Next,最后点击完成
当控制台中出现“BUILD SUCCESS”,项目创建成功
2、加载依赖
在pom.xml文件中添加Spring依赖和日志相关依赖
<dependencies> <!--测试相关--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--Spring核心基础依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</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.17</version> </dependency> </dependencies>
3、代码实现
在main目录下面创建java和resources目录
分别在java和resources目录上点击右键,分别选择Mark Directory as-->Sources Root 和 Mark Directory as -->Resources Root,设置为源码目录和资源目录
创建dao包,在dao包下创建TestDao接口和TestDao接口的实现类,结构如下图:
TestDao接口代码示例:
package dao; public interface TestDao { public void sayHello(); }
TestDaoImpl实现类代码示例:
package dao; public class TestDaoImpl implements TestDao { @Override public void sayHello() { System.out.println("Hello,Spring!"); } }
在resources资源目录点击右键,依次选择New-->XML Configuration File-->Spring Config,创建applicationContext.xml的配置文件
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"> <!--把testDao对象的创建权交给Spring--> <bean id="testDao" class="dao.TestDaoImpl"></bean> </beans>
创建test包,在test包下创建测试类SpringTest
SpringTest类代码示例:
package test; import dao.TestDao; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { @Test public void demo(){ //初始化Spring容器ApplicationContext,加载配置文件 ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml"); //通过容器获取testDao实例 TestDao testDao = (TestDao) application.getBean("testDao"); testDao.sayHello(); } }
点击测试方法左侧的运行按钮,选择Run,测试代码
运行后控制台显示结果
到此项目运行成功!