使用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