美文网首页
01 hello world

01 hello world

作者: hayes0420 | 来源:发表于2018-05-12 17:18 被阅读0次

    早前跟着马士兵老师的视频学习了一下spring,动手比较少,没什么深刻的理解。今天开始从头下手对spring了解一下。

    代码结构如下:


    image.png
    
    
    public class HelloWorld {
        private String name;
        public void setname(String name) {
            System.out.println("setname:"+name);
            this.name=name;
        }
        public void hello(){
            System.out.println("hello "+name);
        }
        public HelloWorld(){
            System.out.println("hello world construct");
        }
    
    }
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
        public static void main(String[] args) {
            //HelloWorld hellow= new HelloWorld();
            //hellow.setname("Spring test");
            ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
            //HelloWorld hellow = (HelloWorld)ctx.getBean("helloWorld");
            //hellow.hello();
        }
    
    }
    
    

    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-2.0.xsd">
    
        <bean id="helloWorld" class="com.lyc.spring.HelloWorld">
            <property name="name" value="Spring_HelloWorld"></property>
        </bean>
    
    </beans>    
    

    输出结果看spring完成的class的实例化,构造函数。接下来就能直接调用了。

    这样就引入了控制反转IOC:
    传统都是new一个对象出来调用。现在交给了Spring容器创建需要的对象。通俗来讲有个司机开车需要自己动手,控制反转就是自己不动手开车,而是设置程序自动驾驶

    相关文章

      网友评论

          本文标题:01 hello world

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