IDEA 使用内置 Maven 创建一个 Spring 项目
创建 Maven 项目
首先,New Project
next,
这里的 Name 是项目的名称,然后修改包名,这里的 ArtifactId 默认和项目的 Name 保持一致。
next,
我这里的 3 个选项全部保持默认,这里要注意一点,这个
C:\Users\用户名\.m2\setting.xml
文件默认是不存在的,然后这时 IDEA 在项目中就会自动去其内置的 Maven
中寻找配置文件,其在文件中的路径默认为
C:\Program Files\JetBrains\IntelliJ IDEA 2021.1.2\plugins\maven\lib\maven3\conf
,如下
然后我们添加 Maven 的阿里云镜像也是直接修改这个文件,如下,在
setting.xml
中添加如下代码
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
由于我这里的 repository 使用的默认的位置,所以我就没有配置本地的 repository。需要配置时再到网上搜索相关配置进行配置即可。
然后 finish。
这里可能会出现
No archetype found in remote catalog. Defaulting to internal catalog.
这样的警告,这个问题是由阿里云的仓库导致的,我在使用官方默认的仓库(需要科学上网)就不会出现这样的问题。不过,这个警告不会对项目产生什么大的影响。
我们运行一下默认的项目,得到如下的结果
Spring 相关配置
首先,去 Maven 的中央仓库(https://mvnrepository.com/)
然后将上面的代码框中的代码复制下来,并粘贴到 IDEA 的 pom 文件下
右键 main 目录,在下面新建一个 resources 目录,
IDEA 有自动提示的 resources 目录,点击创建即可
然后在 resources 目录下创建一个 beans.xml
配置文件
接下来我们就简单写个类测试一下。
首先写一个 Student 类
package com.hust.bean;
public class Student {
private String name;
private int age;
private String tel;
public Student() {
}
public Student(String name, int age, String tel) {
this.name = name;
this.age = age;
this.tel = tel;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
然后在 bean.xml
中增加一个 bean,如下
<?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="zhangsan" class="com.hust.bean.Student" scope="prototype">
<property name="name" value="张三"></property>
<property name="age" value="20"></property>
<property name="tel" value="18627158203"></property>
</bean>
</beans>
最后在 App 类中进行测试
package com.hust;
import com.hust.bean.Student;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) factory.getBean("zhangsan");
System.out.println(student.getName() + ":" + student.getAge() + ":" + student.getTel());
}
}
输出结果
张三:20:18627158203
到此,基本就完成了。