spring之第一个spring程序

时间:2022-07-23
本文章向大家介绍spring之第一个spring程序,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

spring具体描述:

  • 轻量级
  • IOC:依赖注入
  • AOP:面向切片编程
  • 容器:spring是一个容器,包含并且管理应用的生命周期
  • 框架
  • 一站式

一、搭建spring开发环境

在eclipse中新建一个java项目,在项目中新建一个lib文件夹,并将以下spring需要的jar包放在lib文件夹下:

选中这五个包,点击鼠标右键,选择bulid path-->add to build path,

最终的项目目录如下:

在src下新建一个包,在包里面新建两个java文件。在src下新建一个Spring bean configure file类型的文件:applicationContext.xml

二、第一个spring程序

HelloWorld.java

package com.gong.spring.beans;

public class HelloWorld {
    public HelloWorld() {
        System.out.println("构造方法");
    }
    private String name;
    public void setName(String name) {
        this.name = name;
    }
    public void show() {
        System.out.println("姓名是:"+this.name);
        
    }
}

Main.java

package com.gong.spring.beans;

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

public class Main {
    public static void main(String[] args) {
        /*
         * 普通的java对象的创建
        HelloWorld helloworld = new HelloWorld();
        helloworld.setName("tom");
        helloworld.show();
        */
        
        //通过spring创建的对象
        //1.创建spring的IOC容器对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.从容器中获取Bean实例
        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld"); 
        //3.调用方法
        helloWorld.show();
    }
}

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 -->
    <bean id="helloWorld" class="com.gong.spring.beans.HelloWorld">
        <property name="name" value="jack"></property>
    </bean>

</beans>

使用spring管理java对象时需要注意的地方:

在applicationContext.xml中,id是标识该类的名称,class是具体的某一个类名。property 是类的属性标识,name代表属性名,value代表值

在Main.java中,先创建IOC容器对象,然后获取Bean实例,getBean()中的名称就是applicationContext.xml中id的内容。

最后输出:

可以看到,该类的构造方法也会被调用。我们可以得出,通过spring获取对象的实例会调用该类的构造方法,并且为相应的属性赋予初始值