初识Spring---Spring的简单例子

Hello.java

package com.Cai.pojo;

import lombok.Data;

/**
 * @Description
 * @Author Cai
 * @Date 2021-03-03 16:33
 */
@Data
public class Hello {
          
   
    private String string;
}

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    id = 变量名
        class = 对象本身,只能写实体类,不能写接口-->

    <bean id="hello" class="com.Cai.pojo.Hello">
        <property name="string" value="Spring"/>
    </bean>

</beans>

MyTest

import com.Cai.pojo.Hello;
import lombok.val;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Description
 * @Author Cai
 * @Date 2021-03-03 16:48
 */
public class MyTest {
          
   
    public static void main(String[] args) {
          
   
//        获取Spring的对象
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        取出对象
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.getString());
    }
}
经验分享 程序员 微信小程序 职场和发展