> 文章列表 > 如何创建Spring项目

如何创建Spring项目

如何创建Spring项目

创建Spring项目

创建一个Maven项目

这里使用的是2023版本的idea。

添加Spring框架支持

在项目的pom.xml中添加Spring支持。这里可以到中央仓库找一下。

<dependencies><!-- https://mvnrepository.com/artifact/org.springframework/spring-context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.19</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>5.3.19</version></dependency></dependencies>

记得要刷新一下

添加启动类

在Java文件夹下创建一个启动类

存储Bean对象

创建Bean

把Bean注册到容器中

添加Spring配置文件spring-config.xml。(放到resources根目录下

<?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="user" class="User"></bean>
</beans><?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="user" class="User"></bean>
</beans>

获取并使用Bean对象

创建Spring

ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");

获取指定的Bean对象

context.getBean("user",User.class);

使用Bean