记录通过maven创建一个Spring工程的基本步骤
- 新建一个maven工程 步骤 new-other-maven project
- 一直点击next 直到这一步 其中 groupId 与Artifact Id 即为项目在maven仓库中的坐标
- 然后在自动生成的pom.xml文件中添加依赖jar包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId> org.springframework</groupId >
<artifactId> spring-context</artifactId >
<version> ${spring.version}</version >
</dependency>
<dependency>
<groupId> org.springframework</groupId >
<artifactId> spring-core</artifactId >
<version> ${spring.version}</version >
</dependency>
<dependency>
<groupId> org.springframework</groupId >
<artifactId> spring-beans</artifactId >
<version> ${spring.version}</version >
</dependency>
<dependency >
<groupId> org.springframework</groupId >
<artifactId> spring-web</artifactId >
<version> ${spring.version}</version >
</dependency>
<dependency>
<groupId> org.springframework</groupId >
<artifactId> spring-webmvc </artifactId>
<version> ${spring.version}</version >
</dependency>
</dependencies>
- 在Resources文件夹中创建Spring的配置文件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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
</beans>
注:若想通过注解的方式进行依赖注入,则在配置文件中加入:
<context:component-scan base-package=""></context:component-scan>
- 新建Container类,并且在无参构造函数中添加输出语句。
在类名上添加注解 @Component
- 在main方法中初始化Spring容器
public static void main( String[] args ){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
此时控制台已经有Container类构造函数的输出了。证明对象已经创建成功。
- 获取对象实例的代码语句
Container container = (Container)context.getBean(Container.class);