美文网首页Java
Java Spring-HelloWorld

Java Spring-HelloWorld

作者: 一亩三分甜 | 来源:发表于2019-12-31 14:28 被阅读0次

Spring-HelloWorld

public class Main {
    public static void main(String[] args) {
        //常用调用
//        doSay();
        //Spring调用
        //1.创建一个Spring的IOC容器对象
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        //2.从IOC容器中获取Bean实例
        HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");
        //3.调用sayHello()方法
        helloWorld.sayHello();
    }

    public static void doSay(){
        //不使用框架之前的步骤
        //1.创建一个HelloWorld对象
        HelloWorld helloWorld = new HelloWorld();
        //2.为实例对象的属性赋值
        helloWorld.setName("Spring");
        //3.调用对象的方法
        helloWorld.sayHello();
    }
}

spring-config.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="helloWorld" class="HelloWorld">
        <property name="name" value="Spring"></property>
    </bean>
</beans>

public class HelloWorld {
    private String name;
    public HelloWorld(){
        System.out.println("This is HelloWorld constructor.");
    }
    public void setName(String name){
        System.out.println("This is HelloWorld setName().");
        this.name = name;
    }
    public void sayHello(){
        System.out.println("Hello " + name);
    }
}
//输出
十二月 31, 2019 2:19:46 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3eb07fd3: startup date [Tue Dec 31 14:19:46 CST 2019]; root of context hierarchy
十二月 31, 2019 2:19:46 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-config.xml]
This is HelloWorld constructor.
This is HelloWorld setName().
Hello Spring

相关文章

网友评论

    本文标题:Java Spring-HelloWorld

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