美文网首页
Spring 初探

Spring 初探

作者: lucus_guo | 来源:发表于2017-04-26 15:46 被阅读0次

    Spring HelloWorld

    Spring 环境配置,这里略过。
    打开eclipse,新建java Project,新建lib文件夹,把spring,依赖的jar包,拷贝到lib目录下,然后 add to build path,项目结构如下图所示。

    Paste_Image.png

    新建HelloWorld.java,代码如下:

    package com.lucus.spring.beans;
    
    public class HelloWorld {
    
        private String name;
        
        public void setName(String name)
        {
            this.name = name;
        }
        
        public void hello()
        {
            System.out.println("hello: " + name);
        }
            
    }
    

    新建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.lucus.spring.beans.HelloWorld">
            <property name="name" value="Spring"></property>
        </bean>
    
    </beans>
    

    然后新建Main.java,进行验证:

    package com.lucus.spring.beans;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
        public static void main(String[] args)
        {
            /*
            //创建helloworld的一个对象
            HelloWorld helloworld = new HelloWorld();
            //为name 属性赋值
            helloworld.setName("lucus");
            */
            //现在有了spring我们可以把前两步交给spring来完成
            
            //1.创建Spring的IOC容器对象
            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
                
            //2.从IOC容器中获取Bean 实例 
            HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");
            
            //调用hello方法.
            helloWorld.hello();
        }
        
    }
    
    

    分析:在Main函数中,主函数通过加载applicationContext.xml文件,spring框架来帮我们,构建HelloWorld对象,通过<property></property>标签,给HelloWorld对象的name属性赋值.

    相关文章

      网友评论

          本文标题:Spring 初探

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