第一个Spring小程序

(1)添加5个jar包到类路径下
这里写图片描述
(2)在类路径下创建bean 配置文件applicationContext.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-4.0.xsd">

</beans>

(3)不使用Spring框架

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

    public void hello(){
        System.out.println("hello:"+name);
    }
}
public class Main {
    public static void main(String[] args) {
        //通过new创建对象
        HelloWorld hello=new HelloWorld();
        //为对象的属性设置值
        hello.setName("Spring");
        //使用对象,调用对象的方法
        hello.hello();
    }
}

在不使用Spring框架时,需要自己去new对象、为对象属性赋值,然后才使用对象。高耦合

下面来看一下怎么使用Spring框架吧
(4)使用Spring
使用Spring之后,对象的创建以及对象属性的赋值都交给了Spring框架。我们直接从Spring的IOC容器中取出装配好的对象,然后使用该对象。

配置文件:

<?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-4.0.xsd">

    <bean id="hello" class="com.HelloWorld">
        <property name="name" value="Spring"></property>
    </bean>

</beans>
public class Main {
    public static void main(String[] args) {
        //创建IOC容器对象
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //从IOC容器获取bean实例
        HelloWorld h=(HelloWorld) context.getBean("hello");
        //调用bean的方法
        h.hello();
    }
}

我们首先要做的就是实例化IOC容器对象,然后才能从容器中获取bean。

实例化IOC容器对象–>从容器中获取bean(已注入属性)–>使用bean

使用Spring框架,不需要自己创建对象,也不用自己为对象的属性赋值(这些工作交给IOC容器完成),却有相同的运行效果。Spring的IOC容器大大降低了耦合度

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值