IOC/DI第一个示例

1.新建Spring项目,

2.src下创建Category

public class Category {
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    private int id;
    private String name;
}

3.src下新建 

<?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 name="c" class="Category">

        <!--name为类属性中的字段名,value为值-->
        <property name="name" value="category 1" />
        <property name="id" value="22"  />     
    </bean>
</beans>

4.TestSpring

/**
 * @ClassName TestSpring
 * @Description TODO
 * @Author Zouch
 * @Date 2020/4/3 9:35
 */
public class TestSpring {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        Category cd = (Category) context.getBean("c");
        System.out.println(cd.getId());
        System.out.println(cd.getName());
    }
}

运行即可获取到对象的属性。

原理:对象由原来的New变成了  Spring管理并生产   这边是IOC(控制反转)的简单理解。

发布了20 篇原创文章 · 获赞 7 · 访问量 812

猜你喜欢

转载自blog.csdn.net/woshizouqi/article/details/105285892