Spring 源码分析(一)--- IOC demo

Spring IOC 容器基本用法

一、先定义一个 Bean

TestBean.java

public class TestBean {
    
    

    private String testStr = "testStr";

    public String getTestStr() {
    
    
        return testStr;
    }

    public void setTestStr(String testStr) {
    
    
        this.testStr = testStr;
    }
}

二、配置 Bean

src/main/resources/beans.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">

    <!-- 使用 spring 创建对象,在 spring 这些都称为Bean -->
    <bean id="testBean" class="com.example.springframework.demo.pojo.TestBean"/>

</beans>

三、使用 Bean

public class Main {
    
    

    /** 日志记录对象。 */
    private static final Logger LOGGER = LogManager.getLogger(Main.class);

    public static void main(String[] args) {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        TestBean testBean = (TestBean) context.getBean("testBean");

        LOGGER.info("testBean testStr" + testBean.getTestStr());
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39651041/article/details/129674546