使用idea, 通过maven新建一个spring项目
-
File --> new --> project -->maven
-
设置项目名称,位置,包名等
-
引入spring framework
3.1 到mvnrepository.com
搜索spring context
3.2 复制引入maven的代码
3.3 将复制到代码粘贴到项目的pom文件中
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.stark</groupId> <artifactId>Test</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.16</version> </dependency> </dependencies> </project>
3.4 点击
load maven change
, 加载引入的spring框架 -
在项目中新建一个Person类
package com.stark; public class Person { }
-
新建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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="person" class="com.stark.Person"/> <!-- 自己输入这一行--> </beans>
-
新建Test类
package com.stark; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Object person = ctx.getBean("person"); System.out.println(person); } }
-
运行main方法. 控制台就会输出
com.stark.Person@1ed4004b
. 这就建好了一个Spring项目com.stark.Person@1ed4004b Process finished with exit code 0