spring基础(1)-基本使用

来源:互联网 发布:格雷厄姆格林知乎 编辑:程序博客网 时间:2024/06/01 08:21
  1. Spring的安装
    Help—EclipseMarketPlace中直接搜索进行安装。
  2. 创建一个spring(HelloWorld)程序
    (1)创建一个Java工程,导入spring所必要包(四个必须包和一个日志包)
    这里写图片描述

  3. 创建spring的配置文件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.atguigu.spring.beans.HelloWorld">        <property name="name2" value="Spring"></property>    </bean></beans>

4.创建一个HelloWorld类

public class HelloWorld {    private String name;    public void setName2(String name) {        System.out.println("setName"+name);        this.name = name;    }    public void hello(){        System.out.println("hello"+name);    }    //调用构造器对配置文件中的bean进行初始化,同时调用set方法对属性进行赋值    public HelloWorld(){        System.out.println("HelloWorld's Constructor...");    }}

5.创建一个Main方法进行测试使用

public class Main {    public static void main(String[] args){        /*//创建HelloWorld 的一个对象,此处的调用等同于下面的Spring调用        HelloWorld helloworld = new HelloWorld();        //为name属性赋值        helloworld.setName("atguiug");*/        //1.创建Spring 的IOC容器对象        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");        //2.从IOC容器中获取bean实例        HelloWorld helloworld = (HelloWorld) ctx.getBean("helloworld");        //调用hello方法        helloworld.hello();    }}

本文章仅作为作者学习的笔记,此类下所有文章均为此用途。

0 0
原创粉丝点击