2021-11-01

建立spring helloword工程

1.建立maven工程

命名为spring-helloword;

在这里插入图片描述

2.导入依赖

在这里插入图片描述

<dependencies>
        <!--webmvc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>
        <!--测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--lombok 依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
    </dependencies>

3.建立helloword类

在这里插入图片描述
@Data:注解在类上,会为类的所有属性自动生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。
需要导入Lombok依赖包才能用@Data注解;

4.建立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就是java对象 ,Spring创建和管理-->
    <bean id="hello" class="com.example.dao.HelloWord">
        <property name="str" value="Spring"/>
    </bean>

</beans>

其中bean中的id对应下面MyTest文件中的getBean;class对应HelloWord类的路径;name是HelloWord类中对应的属性;
value是bean对HelloWord类中属性str的赋值,HelloWord类中只需对属性str声明,初始化是在bean中处理的,即spring在底层处理。

5.建立Test文件

在这里插入图片描述

public static void main(String[] args) {
        //获取spring的上下文对象,
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //对象在spring中管理了,要使用,就去里面取出来。
        HelloWord hello = (HelloWord) context.getBean("hello");
        System.out.printf(hello.toString());
    }

通过ClassPathXmlApplicationContext读取applicationContext.xml配置文件;其中getBean对应 applicationContext.xml文件中bean的id;

6.结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值