美文网首页
用 Maven 创建 Spring 的项目

用 Maven 创建 Spring 的项目

作者: 码农UP2U | 来源:发表于2020-07-16 05:17 被阅读0次

使用 Maven 创建一个 Spring 的项目,然后在 pom.xml 文件中引入 Spring 的依赖,引入一个即可。

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>

Maven 项目会为我们创建两个目录,一个是 java 目录,一个是 resource 目录,在 resource 目录下添加 spring 的配置文件 applicationContext.xml 。

然后在 java 目录下创建一个包,然后定义一个 Person 类,类的定义如下:

public class Person {
    private String name;
    private String gender;

    public Person() {
    }

    public Person(String name, String gender) {
        this.name = name;
        this.gender = gender;
    }

此处省略了 getter 和 setter 方法。

有了这个类,我们就可以在 applicationContext.xml 文件中定义这个类,来让 Spring 来管理这个类。在 applicationContext.xml 文件中关于 Person 类的定义如下:

<bean id="person" class="com.test.spring.Person"></bean>

这样,我们的类就可以被 Spring 进行管理了。

创建一个测试类 Test,并定义一个 main 方法来测试这个类。

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        Person person = ac.getBean("person", Person.class);

        System.out.println(person);
    }
}

可以看出,我们并没有去实例化 Person 的对象,但是却可以得到一个 Person 的对象。因为在 Spring 启动的时候已经为我们实例化了一个 Person 类,我们只要使用 ApplicationContext 对象的 getBean 方法即可得到 Person 的对象。

刚开始学习 Spring 框架,慢慢记录!有错误请指正。



微信中搜索 “码农UP2U” 关注我的公众号吧!!!

相关文章

网友评论

      本文标题:用 Maven 创建 Spring 的项目

      本文链接:https://www.haomeiwen.com/subject/fxzjhktx.html