spring ioc

传统方式
=====================UserService ===================
public interface UserService {
    public void sayHello();
}


=====================UserServiceImpl===================
public class UserServiceImpl implements  UserService{

    // 添加属性:
    private String name;

    public void sayHello() {
        System.out.println("Hello Spring" + name);
    }

    public String getName() {
        return name;
    }

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

======================SpringDemo1 ====================
public class SpringDemo1 {

    @Test
    /**
     * 传统方式开发
     */
    public void demo1(){
        // UserService userService = new UserServiceImpl();
//由于接口没有name属性,所以。只能用实现类,不能使用接口的形式
        UserServiceImpl userService = new UserServiceImpl();
        // 设置属性
        userService.setName("张三");
        userService.sayHello();
    }
}

==============applicationContext.xml======================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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">
    <!-- UserService的创建权交给了Spring -->
   <bean id="userService" class="com.imooc.ioc.demo1.UserServiceImpl">
        <property name="name" value="李四"/>
    </bean>
</beans>

=====================springDemo1.java======================
    /**
     * Spring的方式实现
     */
    @Test
    public void demo2(){
        //创建spring的工厂
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过工厂获得
        UserService userService=(UserService) applicationContext.getBean("userService");

        userService.sayHello();
    }

 

转载于:https://my.oschina.net/popfei/blog/1830305

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值