Spring学习笔记——入门篇

一. 创建一个Spring项目

1. create New Project —> Spring —> next

这里写图片描述

2. 创建项目名和项目保存路径,最后点击finish,要连网, 因为会自动下载所需的jar包

这里写图片描述

3. 创建好的目录结构

这里写图片描述
这样就完成了Spring项目的创建

二 .编写一个Hello World

1. 在src文件加下创建一个applicationContext.xml文件,文件的内容,这个文件是用来配置Bean的, 刚开始创建的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" 
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

2. 创建一个包, 包名叫 com.hzj.spring.bean,在com.hzj.spring.bean包下创建一个java文件,叫做HelloWorld,里面的内容如下

package com.hzj.spring.bean;

public class HelloWorld {

    private String name;
    private String name1;


    public HelloWorld() {
        System.out.println("Helloworld...");
    }

    public void setName(String name) {
        System.out.println("HelloWorld set ...");
        this.name = name;
    }

    public void setName1(String name1) {
        System.out.println("helloWorld set1 ...");
        this.name1 = name1;
    }

    public void hello() {
        System.out.println("hello  + " + name);
    }

}

3. 更改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" 
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--配置Bean, 会自动创建HelloWorld实例, 并且调用HelloWorld的空构造方法-->
    <bean id="helloWorld" class="com.hzj.spring.bean.HelloWorld">
        <!--调用HelloWorld的setName方法-->
        <property name="name" value="spring"></property>
        <!--调用HelloWorld的setName1方法-->
    <property name="name1" value="Spring1"></property>
    </bean>
</beans>

4. 在com.hzj.spring.bean包下创建一个测试类Main,代码如下

package com.hzj.spring.bean;

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

public class Main {
    public static void main(String[] args) {
        //传统的方法
        /*HelloWorld helloworld = new HelloWorld();
        helloworld.setName("hzj");
        helloworld.hello();
        */
        //创建Spring 的ioc容器对象
        //ClassPathXmlApplicationContext: 从类路径下加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //从IOC容器中获取Bean的实例
        //利用id定位到IOC容器中的Bean
        HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloWorld");
        //利用类型返回IOC容器中的Bean, 但要求IOC容器中必须只有一个该类型的Bean
        //HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
        //调用hello的方法
        helloWorld.hello();
    }
}

5. 最终项目的目录结构为

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hzjanger/article/details/82391512