Spring QuickStart

简单的HelloSpring项目

第一步 导入jar包

<!--Spring的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>

导入该jar包后可以可以导入其他相关的Springjar包


第二步 编写代码

编写一个hello的实体类

public class Hello {
    private String name;

    public String getName() {
        return name;
    }

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

    public void show() {
        System.out.println("Hello = " + name);
    }
}

2.编写我们的spring文件,文件名为beans.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.xsd">

<!--bean就是java对象,由spring创建和管理-->
    <bean id="hello" class="com.evilposeidon.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>
</beans>

3.测试

public class Test {
    @org.junit.Test
    public void test() {
        //解析beans.xml 生成管理相应的bean对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //getBean:参数为spring配置文件中的bean的id
        Hello hello = context.getBean(Hello.class, "hello");
        hello.show();
    }
}

思考

1.hello的对象怎么来的? :Spring创建的
2.hello对象的属性怎么设置的?:有Spring容器设置的
上述的示例就是控制反转的一个展示
控制权在Spring手里,对象是由Spring创建的,传统的应用程序是由程序本身创建的
程序由创建对象反转成被动的接受对象,这就是反转
依赖注入是通过set方法进行注入的
IOC是一种编程思想,主动编程变为被动接受的思想

猜你喜欢

转载自www.cnblogs.com/evilposeidon/p/13369683.html
今日推荐