zoukankan      html  css  js  c++  java
  • Spring之HelloWorld

    学习Spring也是在在尚硅谷上学的,里面老师讲的很详细,所以我就把老师讲的内容全部手写一遍,收获颇多

    先进行Spring的入门

    首先新建一个类HelloWorld

    public class HelloWorld {
        private String name;
        public void hello(){
            System.out.println("hello:"+getName());
        }
        public void setName(String name) {
    System.out.println("set method");
            this.name = name;
        }
        public String getName() {
                    return name;
        }
        public HelloWorld() {
            System.out.println("constructor start");
        }
    }

    之后再当先项目下新建一个XML文件取名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-3.1.xsd">
        
        <bean id="helloWorld" class="com.auguigu.spring.beans.HelloWorld">
            <property name="name" value="lisi"></property>
        </bean>
    
    </beans>

    之后再新建一个测试类Main

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
        
        public static void main(String[] args) {
            
            //创建spring的IOC容器对象
            ApplicationContext ctx = new ClassPathXmlApplicationContext("./applicationContext.xml");
            //从IOC容器中获取bean实例
            HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
            //调用hello方法
            helloWorld.hello();
        }
    }

    下面是执行结果:

    log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    constructor start
    set method
    hello:lisi

    其中构造器和set方法是在创建IOC容器对象时执行的

    配置bean时,通过反射的方式在IOC容器中创建bean,所以要求bean中必须有无参构造器

    ApplicationContext代表IOC容器

    ClassPathXmlApplicationContext是ApplicationContext接口的实现类,该实现类从类路径下来加载xml文件

  • 相关阅读:
    01 Java基础第一天
    2019牛客暑期多校训练营(第七场)J A+B problem
    SDNU 1477.矩形面积交(思维)
    SDNU 1194.传纸条(DP)&& 1032.机器人
    SDNU 1280.就问你慌不慌(高精度)
    POJ 2528 Mayor's posters(线段树+离散化)
    HDU 1698 Just a Hook(线段树区间赋值)
    POJ 3468 A Simple Problem with Integers (区间加区间查找)
    HDU 1754 I Hate It(线段树单点更改、区间查找最大值)
    HDU 1166 敌兵布阵(线段树单点加区间查询)
  • 原文地址:https://www.cnblogs.com/sdnu-zhang/p/8527256.html
Copyright © 2011-2022 走看看