JavaEE第三课 | spring入门程序的编写

141 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

Spring的入门程序

Step One-创建类

我们在Maven的pom.xml中添加完spring的依赖之后,然后在src/main/java目录下创建com.xxx(随意取名)包,然后再该包下创建名为HelloSpring(随意取名)的一个类。

  • 代码如下:
package com.xxx;

public class HelloSpring {
    private String userName;  //定义uaerName属性
                
    public void setUserName(String userName) {  
        this.userName = userName;
    }
     //show方法
    public void show(){

        System.out.println (userName+",你好,Spring");
    }
}

Step Two-创建applicationContext.xml文件

在项目的src/main/resources目录下面新建applicationContext.xml文件作为HelloSpring类的配置文件,并在该配置文件中创建id为helloSpring的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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloSpring" class="com.yuanshuo.HelloSpring">
        <property name="userName" value="某某"></property>
        <!-- collaborators and configuration for this bean go here -->
    </bean>



    <!-- more bean definitions go here -->

</beans>

Step Three- 创建测试类

在项目的src/test/com.xxx文件夹下创建测试类HelloSpringTest,在main()方法中初始化容器并加载applicationContext.xml配置文件,通过Spring容器获取HelloSpring容器并加载applicationContext.xml配置文件,通过Spring容器获取HelloSpring类的实例,调用HelloSpring类中的show()方法在控制台中输出信息

package com.yuanshuo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class HelloSpringTest {
    public static void main(String[] args) {
        //1、获取spring容器
        ApplicationContext ac=new ClassPathXmlApplicationContext ("applicationContext");
        //2、从spring容器中获取对象
        HelloSpring helloSpring=(HelloSpring)ac.getBean ( "helloSpring" );
        //3、调用对象方法
        helloSpring.show ();
    }

}

Step four- 在idea中启动测试类

在idea中启动测试类HelloSpringTest,控制台输出结果:

1664720580978.png

外:Spring帮助文档获取约束信息

当我们需要一些配置文件的模板、约束信息时,我们可以去Spring的官网中查看,也可以下载到本地查看。