Spring(1)--Spring项目创建

本文介绍如何使用Maven创建Spring项目,包括配置pom.xml依赖、编写applicationContext.xml配置文件及实现类间依赖注入的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring项目创建

maven方式创建:

  • 创建maven java项目
  • pom.xml添加Spring框架的依赖
  • 创建beans.xml,声明需要Spring框架去自动实例化类成员的类,以及自动实例化的类
  • 编写测试类,测试类中对象的自动实例化;classA持有classB,classA和classB都在beans.xml中进行声明,在测试类中通过context.getBean()的方式获取到classA的对象,调用classA.methodA()中调用classB.mehodB(),来验证classB被自动实例化成功

pom.xml中的dependency依赖

<dependencies>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.3</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
</dependencies>

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="service" class="hello.MessagesService"></bean>
    <bean id="printer" class="hello.MessagePrinter">
        <property name="service" ref="service"></property>
    </bean>
</beans>

applicationContext创建的位置,新建resources文件夹,设置为文件夹目录(项目创建后一般在main目录下会有resources资源目录)

applicationContext.xml创建的时候可以resource --New–XML Configuration File–Spring

在这里插入图片描述

要实例化的类MessagePrinter, MessagesService

package hello;

public class MessagePrinter {
    private MessagesService service;
    public MessagePrinter() {
        System.out.println("MessagePrinter");
    }

    public MessagesService getService() {
        return service;
    }

    //需要添加set方法,与applicationContext.xml中printer--property--name的值对应
    public void setService(MessagesService service) {
        this.service = service;
    }

    public void printMessage(){
        System.out.println(service.getMessage());
    }
}
package hello;

public class MessagesService {
    public MessagesService() {
        System.out.println("MessageService....");
    }

    public String getMessage(){
        return "Hello World";
    }
}

实例化ApplicationContext

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();

运行结果:

在这里插入图片描述

对于Spring的理解:不用new去实例化对象,通过*.class对象就能够得到对象,并且只需要配置好applicationContext.xml,类中持有的对象也能够一并实例化

参考:

IDEA使用maven搭建spring项目

Spring学习(1)——快速入门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值