2.HelloSpring

思考问题?

  • Hello对象是谁创建的?

    Hello对象是由Spring设置的

  • Hello 对象的属性是怎么设置的?

    Hello 对象的属性是Spring容器设置的

这个过程就叫控制反转

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

反转:程序本身不创建对象,而变成被动的接受对象。

依赖注入:就是利用set方法来进行注入的。

IOC是一种编程思想,由主动的编程变成被动的接收。

可以通过ClassPathXmlApplicationContext去浏览一下底层源码。

OK,到了现在,我们彻底不用再回程序中改动了,要是现任不同的操作,只需要再xml配置文件中进行修改,所谓的IOC,一句话搞定:对象由Spring来创建,管理,装配!

1、由项目一一探究

  • 创建了一下新的maven包:spring-02-hellospring

    • 在main的java创建一个Hellojavaclass文件

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

    • 创建beans.xml FIeld

      852        
  • test的java

    • 创建名为 MyTest 的 javaclass

      import com.jan.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("beans.xml");        //我们的对象现在都在Spring中管理了,我们要使用直接去里面取出来就可以了!        //   context.getBean("hello")-- Hello hello = context.getBean("hello")        Hello hello = (Hello) context.getBean("hello");        System.out.println(hello.toString());    }}

2、项目二:Spring开始的maven 进行控制反转

  • 所有的UserDao、UserDaoImpl、UserDaoMysqlImpl、UserDaoOracleImpl、UserDaoSqlserverImpl、UserService、UserServiceImpl均无变化

  • 配置beans.xml

                                    <!-- 只需修改 ref 里面的值就可以了                  -->    
  • MyTest 的修改

    import com.jan.dao.UserDaoImpl;import com.jan.dao.UserDaoSqlserverImpl;import com.jan.dao.service.UserService;import com.jan.dao.service.UserServiceImpl;import com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {    public static void main(String[] args) {        /*  原来之前的调用        UserService userService = new UserServiceImpl();        用户实际调用的是业务层,dao层它们不需要接触!        ((UserServiceImpl) userService).setUserDao(new UserDaoImpl());//userService.setUserDao        userService.getUser();        */               //去获取ApplicationContext:拿到Spring的容器      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");        //容器在手,天下我有,就直接get谁!        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");        userServiceImpl.getUser();    }}