Spring控制反转

spring控制反转(ioc)是为了降低对象之间的耦合性,在没使用ioc之前都是在a对象内部new一个b对象去使用,这样对象之间的耦合性太高,控制反转就是为了降低对象之间的耦合性,所有对象的控制权都交给了第三方容器IOC,由IOC来帮忙创建及注入依赖对象

首先新建一个Student接口及其实现类

//接口
public interface Student {

    void get();
}

//实现类
public class StudentImpl implements Student {

    private  String name;


    public void setName(String name) {
        this.name = name;
    }

    public void get() {
        System.out.println(this.name);

    }
}

然后新建一个bean.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">
    <beans>
        <bean id="stu" class="Test.StudentImpl">
            <property name="name" value="小明"/>
        </bean>
    </beans>
</beans>

这里说下id可以随便取,class为实现类,property是属性

public class Test {
    public static void main(String[]args){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        Student s=context.getBean("stu", Student.class);
        s.get();

    }
}

最后就会执行get方法打印出小明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值