Spring_01_HelloWorld

Hello World

  1. 创建Java项目(HelloSpring)

  2. 添加必要的依赖库

  3. 创建源文件 HelloWorld.java 和 MainApp.java

    HelloWorld.java

    package com.tutorialspoint;
    
    public class HelloWorld {
    private String message;
    
    public String getMessage() {
    return message;
    }
    
    public void setMessage(String message) {
    this.message = message;
    }
    
    }
    

    MainApp.java

    package com.tutorialspoint;
    
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;
    
    public class MainApp {
    public static void main(String[] args) {
        /**
         * 第一步我们使用框架API ClassPathXmlApplicationContext() 来创建应用程序的上下文
         * 这个API加载beans的配置文件,并最终基于所提供的APi,它处理创建初始化所有的对象,即在配置文件中的beans
         * 
         * 第二步 是使用已经创建的上下文**getBean()方法来获得所需的Bean,
         * 这个方法使用Bean的ID返回一个最终可以转换为实际对象的通用对象,
         * 一旦有了对象,你就可以使用这个对象调用这个类的任何方法.
         * 
         */
        XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(
                "Beans.xml"));
        HelloWorld obj = (HelloWorld) factory.getBean("helloworld");
        HelloWorld2 obj2 = (HelloWorld2) factory.getBean("helloworld2");
        String message = obj.getMessage();
        String message2 = obj2.getMessage();
        System.out.println(message);
        System.out.println(message2);
    }
    }
  4. 创建bean的配置文件

    <?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-3.0.xsd">
    
    <bean id="helloworld" class="com.tutorialspoint.HelloWorld">
    <property name="message" value="Hello World    我来在Bean"></property>
    </bean>
    <bean id="helloworld2" class="com.tutorialspoint.HelloWorld2">
    <property name="message" value="Hello World2    我来在Bean "></property>
    </bean>
    
    </beans>
  5. 运行程序

    Hello World    我来在Bean
    Hello World2    我来在Bean 

个人学习总结:

  1. 通过工厂类去加载Beans.xml文件,并解析其中的bean,实例化每个对象

  2. 通过bean的id获得bean中的id获得bean的实例对象

  3. 通过调用getMessage()方法,可以将在bean中初始化的值拿出来

  4. 可以通过message得到值的原因是因为bean中已经将值注入进去了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值