美文网首页spring零基础学习
spring学习2(环境搭建)

spring学习2(环境搭建)

作者: 又是那一片天 | 来源:发表于2017-07-10 15:40 被阅读0次

    spring第一个程序HelloWorld

    1新建java项目
    2导入一下jar
    image.png
    3新建HelloWorld
    package chen;
    public class HelloWorld {
        private String name;
        public void hello() {
            System.out.print(name);
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    
    
    4配置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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="hello" class="chen.HelloWorld">
            <property name="name" value="你好 Spring"></property>
        </bean>
    </beans>
    
    
    5程序入口
    package chen;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
    public static void main(String[] args) {
        
            // 1.创建ioc容器对象
            //ApplicationContext代表ioc容器
            //ClassPathXmlApplicationContext:是ApplicationContext的实现类 从类路径下加载配置文件
            ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
            
            // 2.从ioc容器中获取bean实例
            //利用id获取实例
            //HelloWorld hWorld = (HelloWorld) ctx.getBean("hello");
            //利用类型获取实例 但类型唯一
            HelloWorld hWorld =  ctx.getBean(HelloWorld.class);
            
            // 3.调用方法
            hWorld.hello();
    }
    
    }
    
    

    项目结构如下:


    image.png

    我们的第一个spring 程序就完成了

    • ApplicationContext代表ioc容器
    • ClassPathXmlApplicationContext:是ApplicationContext的实现类 从类路径下加载配置文件

    总结:

    • 配置spring bean配置文件
    • 创建ioc容器对象
    • 从ioc容器中获取bean实例
    • 调用方法
      下一篇 spring学习3

    相关文章

      网友评论

        本文标题:spring学习2(环境搭建)

        本文链接:https://www.haomeiwen.com/subject/bbnyhxtx.html