Spring的第一个程序 HelloSpring

创建实体类:

package com.king.pojo;

/**

*/
public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

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

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

使用Spring来创建对象,在Spring这些都称为Bean

类型 变量名 = new 类型();

Hello hello = new Hello();

id = 变量名

class = new 的对象

property 相当于给对象中的属性设置一个值!

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

    <!-- ApplicationContext.xml配置文件 -->
    <bean id="hello" class="com.king.pojo.Hello">
        <property name="str" value="HelloSpring"/>
    </bean>

</beans>

测试类

import com.king.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //我们的对象现在都在Spring中管理了,我们要是使用,直接去里面取出来就可以!
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello);
    }
}

4.2 小结

到此为止,不用再去程序中改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话:对象由Spring来创建,管理,装配!

<!-- ApplicationContext.xml 的bean中的property标签的属性 -->
ref:引用Spring容器中创建好的对象
value: 具体的值,基本数据类型!

猜你喜欢

转载自www.cnblogs.com/KingTL/p/12945070.html