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文件

posted @ 2018-03-08 11:13  凌羽1025  阅读(86)  评论(0编辑  收藏  举报