Spring-helloworld

本文介绍了如何在Spring框架中实现控制反转,通过XML配置管理对象的创建,并演示了依赖注入的使用。通过实例展示了如何使用`ApplicationContext`获取并操作bean,以及如何将DAO和Service解耦。
摘要由CSDN通过智能技术生成

Spring之helloword(主要理解控制反转)

主要理解控制反转:创建对象的主动权由程序交给了用户

Spring框架中,将使用new关键字创建对象改为了利用xml文件写bean并交给SpingIOC容器去管理

<?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">

    <bean id="hello" class="com.psy.pojo.Hello">
        <property name="str" value="Hello World!"/>
    </bean>

</beans>

// 实体类
package com.psy.pojo;

public class Hello {
    String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

// 测试类
public class MyTest {
    /**
     * 对象的创建交给Spring管理,不再使用new关键字去创建对象了
     */
    @Test
    public void test() {
        // 获取Spring的上下文对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        // 我们的对象现在都在Spring中管理了,要使用,直接去里面取出来就可以了
        Hello hello = (Hello) ac.getBean("hello");
        System.out.println(hello.toString());
    }
}
  • hello对象是谁创建的?
    • hello对象是Spring容器创建的
  • 属性是谁设置的
    • 属性也是Spring容器设置的

这个过程就叫做控制反转:

控制:谁来控制对象的创建,传统的是由程序本身控制创建。Spring之后,对象是由Spring创建

反转:程序本身不创建对象,变成了被动的接收对象

依赖注入:利用set方法进行注入(实体类中必须有set方法)

IOC是一种编程思想,由主动的编程变成被动的接收

接上一个SpringIOC理论推导

将上次代码中的实体类交由Spring容器进行托管,也实现了dao层对象不是在Service层创建出来的

    @Test
    public void test3() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) context.getBean("userServiceImpl");
        userService.getUser();
    }
<?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">

    <bean id="userDaoImpl" class="com.psy.dao.UserDaoImpl"/>
    <bean id="userMysqlImpl" class="com.psy.dao.UserMySqlImpl"/>
    <bean id="userOracleImpl" class="com.psy.dao.UserOrcalImpl"/>

    <bean id="userServiceImpl" class="com.psy.service.UserServiceImpl_2">
        <property name="userDao" ref="userOracleImpl"/>
    </bean>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值