第一个Spring小程序

来源:互联网 发布:优化企业家发展环境 编辑:程序博客网 时间:2024/06/05 08:20

(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容器大大降低了耦合度

原创粉丝点击