zoukankan      html  css  js  c++  java
  • Spring-----ioc

     什么是spring,它能够做什么?

    Spring是一个开源框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。
    Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。
    然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。
    目的:解决企业应用开发的复杂性
    功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
    范围:任何Java应用
    简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

    用一张图来了解Spring

    Spring在这里相当于一个万能胶的作用   就是让对象与对象(模块与模块)之间的关系没有通过代码来关联,都是通过配置类说明
    管理的(Spring根据这些配置 内部通过反射去动态的组装对象)

    什么是控制反转(或依赖注入)
    控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
    IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)” ,即由容器动态的将某种依赖关系注入到组件之中
    案例:实现Spring的IoC

    IOC/DI
    将以前由程序员实例化对象/赋值的工作交给了spring处理

    spring管理bean的方式
    * set注入
         * 基本数据类型
         * 引用数据类型
    * 构造注入
    * 自动装配

    用代码来了解一下set注入(基本数据类型)

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.psy</groupId>
        <artifactId>spring</artifactId>
        <packaging>war</packaging>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring Maven Webapp</name>
        <url>http://maven.apache.org</url>
        <properties>
            <spring.version>5.0.1.RELEASE</spring.version>
            <javax.servlet.version>4.0.0</javax.servlet.version>
            <junit.version>4.12</junit.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            <!-- 2、导入spring依赖 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- 5.1、junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
            <!-- 5.2、servlet -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>${javax.servlet.version}</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
        <build>
            <finalName>T224_spring</finalName>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    web.xml

    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
      <display-name>Archetype Created Web Application</display-name>
    </web-app>

    Spring-context.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"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    
        <bean id="userAction" class="com.psy.ioc.web.UserAction">
            <property name="uid" value="22"></property>
            <property name="uname" value="zs"></property>
            
            <property name="hobby">
                <list>
    
                    <value>rap</value>
                    <value>rap2</value>
                </list>
            </property>
        </bean>
    </beans>

    写一个接口两个实现类 

    web层以及测试类

    UserAction

    package com.psy.ioc.web;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.psy.ioc.biz.UserBiz;
    import com.psy.ioc.biz.UserBizImpl1;
    import com.psy.ioc.biz.UserBizImpl2;
    
    /**
     * 弊端: 
     * 当需求变化非常快的时候 不便于维护。因为维护的权利是属于程序员的
     * 
     * spring的IOC就是解决这一问题的 
     * 将维护代码的权利由程序员转交给spring容器来完成
     * 
     * 
     * 1.spring管理bean的方式
     *  set注入
     *      基本数据类型 
     *      引用数据类型 
     *  构造注入 
     *  自动装配
     * 
     * @author Admin
     *
     */
    public class UserAction {
    
        private UserBiz userBiz = new UserBizImpl2();
        private int uid;
        private String uname;
        private List<String> hobby = new ArrayList<String>();
    
         public int getUid() {
         return uid;
         }
        
         public void setUid(int uid) {
         this.uid = uid;
         }
        
         public String getUname() {
         return uname;
         }
        
         public void setUname(String uname) {
         this.uname = uname;
         }
    
        public List<String> getHobby() {
            return hobby;
        }
    
        public void setHobby(List<String> hobby) {
            this.hobby = hobby;
        }
    
        public UserAction() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        public UserAction(int uid, String uname) {
            super();
            this.uid = uid;
            this.uname = uname;
        }
    
        /**
         * set注入
         */
        public void test1() {
    
            System.out.println("uid" + this.uid);
            System.out.println("uname" + this.uname);
            System.out.println("hobby" + this.hobby);
        }
    
        /**
         * 构造注入
         */
        public void test2() {
    
        }
    
        public void test3() {
            userBiz.read();
        }
    
    }

    测试类:

    /**  
     * 模拟浏览器请求  请求后台
     * @author Admin
     *
     */
    public class Demo1 {
    
        public static void main(String[] args) throws Exception{
            
            UserAction userAction=new UserAction();
            userAction.test1();
            
            
            
            
        }
    
    }

    打印结果就是我们在Spring-context.xml定义的值

    set注入(引用数据类型)

    定义private UserBiz userBiz;    并且提供setget方法

    Spring-context.xml中

    <bean id="userBiz" class="com.psy.ioc.biz.UserBizImpl2"></bean>
    <property name="userBiz" ref="userBiz"></property>

    构造注入同理

    我们将set方法注释,加入构造函数

    同时Spring-context.xml改成

    <constructor-arg name="uid" value="22"></constructor-arg>
            <constructor-arg name="uname" value="zs"></constructor-arg>

    测试方法:

    /**  
     * 模拟浏览器请求  请求后台
     * @author Admin
     *
     */
    public class Demo1 {
    
        public static void main(String[] args) throws Exception{
            
    //        UserAction userAction=new UserAction();
    //        userAction.test1();
            
            
            ApplicationContext context= new ClassPathXmlApplicationContext("/spring-context.xml");
            UserAction bean = (UserAction) context.getBean("userAction");
            bean.test1();
            
        }
    
    }

    自动装配:

    在Spring-context.xml中加入这样一行

    default-autowire="byType"

    注释掉<!-- <property name="userBiz" ref="userBiz"></property> -->也能达到想要的效果

    当然这样的前提是spring的上下文只管理一个

    如果我们想要管理多个

    <bean id="userBiz" class="com.psy.ioc.biz.UserBizImpl1"></bean>
            <bean id="userBiz2" class="com.psy.ioc.biz.UserBizImpl2"></bean>

    将“byType”改成“ByName”

    default-autowire="byName"

    tomcat管理spring

    如何将spring的上下文交给tomcat上下文进行管理

    首先spring上下文为什么Tomact?
    分析:目前工程中的所有javabean都交给了spring进行管理,那么浏览器
    发送请求,请求的是tomcat,由tomcat来处理请求,tomcat处理请求一般来说都要访问数据库
    数据库是由Dao层访问的,Dao层的实体类有事交给spring的上下文管理
    那就意味着,tomcat要处理请求,必须拿到spring的上下文,才能够
    拿到Dao层的Javabean

    SpringLoadListener类:

    /
    @WebListener
    public class SpringLoadListener implements ServletContextListener {
         
        private String springXmlLocation="";
        @Override
        public void contextInitialized(ServletContextEvent sce) {
             System.out.println("监听了tomcat的启动。。。。。");
             ServletContext servletContext =sce.getServletContext();
          springXmlLocation= servletContext.getInitParameter("springXmlLocation");
          if(null ==springXmlLocation|| "".equals(springXmlLocation)) {
              springXmlLocation="/spring_context.xml";
              
          }
             System.out.println("springXmlLocation:"+springXmlLocation);
             ApplicationContext springContext=new ClassPathXmlApplicationContext(springXmlLocation);
             servletContext.setAttribute("SPRING_CONTEXT_KEY", springContext);
        }
        
    }

    UserServlet类:

    @WebServlet("/user")
    public class UserServlet extends HttpServlet {
    
        /**
         * 
         */
        private static final long serialVersionUID = -4749851066001594899L;
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
        
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext servletContext=req.getServletContext();
            ApplicationContext springContext=(ApplicationContext) servletContext.getAttribute("SPRING_CONTEXT_KEY");
            UserAction bean=(UserAction) springContext.getBean("userAction");
            bean.test3();
            
        }
        
    }

    web.xml:

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
        id="WebApp_ID" version="3.1">
      <display-name>Archetype Created Web Application</display-name>
      <context-param>
        <param-name>springXmlLocation</param-name>
        <param-value>/spring_context.xml</param-value>
      </context-param>
    </web-app>
  • 相关阅读:
    用户控件赋值
    计算一串数字中每个数字出现的次数
    如何理解c和c++的复杂类型声明
    STM32 NVIC学习
    stm32f10x_flash.c中文版
    IBM中国研究院Offer之感言——能力是一种态度
    对于STM32别名区的理解 (转载)
    STM32时钟学习之STM3210X_RCC.H解读
    STM32 DMA
    STM32 内部时钟输出PA.8(MCO)
  • 原文地址:https://www.cnblogs.com/psyu/p/11234764.html
Copyright © 2011-2022 走看看