Spring——HelloSpring第一个项目

首先创建实体类

package com.yl.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 + '\'' +
               '}';
  }
}

在recourses目录下创建一个spring配置文件:beans.xml

<?xml version="1.0" encoding="GBK"?>
<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
       https://www.springframework.org/schema/beans/spring-beans.xsd">

   <!--使用Spring来创建对象,在Spring中这些都成为Bean
   类型 变量名 = new 类型();
   Hello hello = new Hello();
   bean = 对象 new Hello();
   id = 变量名
   class = new的对象
   property 给对象中的属性赋值
   -->
   <bean id="hello" class="com.yl.pojo.Hello">
       <property name="str" value="Spring"/>
   </bean>

</beans>

测试:

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

到目前为止,已经彻底不用在程序中改动了,要实现不同的操作,只需要在xml配置文件中进行修改,对象由Spring来创建 管理和装配

 

对应改造上一个程序:

  • 增加配置文件

    <?xml version="1.0" encoding="GBK"?>
    <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
           https://www.springframework.org/schema/beans/spring-beans.xsd">
       <bean id="mysqlImpl" class="com.yl.dao.UserDaoMysqlImpl"/>
       <bean id="oracleImpl" class="com.yl.dao.UserDaoOracleImpl"/>
       <bean id="userServiceImpl" class="com.yl.service.UserServiceImpl">
           <!--
           ref:引用Spring容器中创建好的对象
           value:具体的值,基本数据类型和String
           -->
           <property name="userDao" ref="oracleImpl"/>
       </bean>

    </beans>
  • 测试:

    public static void main(String[] args) {
       //获取ApplicationContext,拿到Spring的容器
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

       //需要什么就直接get什么
       UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
       userServiceImpl.getUser();
    }

 

控制

谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的

反转

程序本身不创建对象,而被动的接收对象

依赖注入

就是利用set方法来进行注入的

 

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

 

posted @ 2020-09-01 17:04  Fabulo  阅读(143)  评论(0)    收藏  举报