• Spring--ioc


     spring 入门

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

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


       简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

    2. 什么是控制反转(或依赖注入)

       控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,
       由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
       IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)”  ,即由容器动态的将某种依赖关系注入到组件之中
       
     IOC/DI
       将以前由程序员实例化对象/赋值的工作交给了spring处理

    3. 如何在spring当中定义和配置一个JavaBean

       3.1 id:在容器中查找Bean的id(唯一、且不能以/开头)
       3.2 class:bean的完整类名
       3.3 name:在容器中查找Bean的名字(唯一、允许以/开头、允许多个值,多个值之间用逗号或空格隔开)
       3.4 scope:(singleton|prototype)默认是singleton
       3.4.1 singleton(单例模式):在每个Spring IoC容器中一个bean定义对应一个对象实例
       3.4.2 prototype(原型模式/多例模式):一个bean定义对应多个对象实例
       3.4 abstract:将一个bean定义成抽象bean(抽象bean是不能实例化的),抽象类一定要定义成抽象bean,非抽象类也可以定义成抽象bean
       3.5 parent:指定一个父bean(必须要有继承关系才行)
       3.6 init-method:指定bean的初始化方法
       3.7 constructor-arg:使用有参数构造方法创建javaBean

     代码演示

      1、ioc中的注入方式

        导入spring需要的pom依赖

     1 <project xmlns="http://maven.apache.org/POM/4.0.0"
     2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     4     <modelVersion>4.0.0</modelVersion>
     5     <groupId>com.yuan</groupId>
     6     <artifactId>T226_Spring</artifactId>
     7     <packaging>war</packaging>
     8     <version>0.0.1-SNAPSHOT</version>
     9     <name>T226_Spring Maven Webapp</name>
    10     <url>http://maven.apache.org</url>
    11     <dependencies>
    12         <dependency>
    13             <groupId>junit</groupId>
    14             <artifactId>junit</artifactId>
    15             <version>4.12</version>
    16             <scope>test</scope>
    17         </dependency>
    18 
    19         <dependency>
    20             <groupId>mysql</groupId>
    21             <artifactId>mysql-connector-java</artifactId>
    22             <version>5.1.44</version>
    23         </dependency>
    24 
    25         <dependency>
    26             <groupId>javax.servlet</groupId>
    27             <artifactId>javax.servlet-api</artifactId>
    28             <version>4.0.1</version>
    29             <scope>provided</scope>
    30         </dependency>
    31         <dependency>
    32             <groupId>org.springframework</groupId>
    33             <artifactId>spring-context</artifactId>
    34             <version>4.3.10.RELEASE</version>
    35         </dependency>
    36 
    37     </dependencies>
    38     <build>
    39         <finalName>T226_Spring</finalName>
    40         <plugins>
    41             <plugin>
    42                 <groupId>org.apache.maven.plugins</groupId>
    43                 <artifactId>maven-compiler-plugin</artifactId>
    44                 <version>3.7.0</version>
    45                 <configuration>
    46                     <source>1.8</source>
    47                     <target>1.8</target>
    48                     <encoding>UTF-8</encoding>
    49                 </configuration>
    50             </plugin>
    51         </plugins>
    52     </build>
    53 </project>

     1. 2、spring-context.xml配置

       注:这里需要安装一个spring插件,也可以不安装,因为我是没有安装的,所以不能介绍给大家,如果有需要的话可以百度查看安装教程

      其实只需要在xml文件中插入一下代码就欧克了!

     1 <beans xmlns="http://www.springframework.org/schema/beans"
     2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     
     4     xmlns:context="http://www.springframework.org/schema/context"
     5     xmlns:tx="http://www.springframework.org/schema/tx"
     6     xmlns:aop="http://www.springframework.org/schema/aop"
     7     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     8        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     9        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    10        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    11 </beans>

     接下来看一下xml的配置

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     default-autowire="byName"
     5     xmlns:context="http://www.springframework.org/schema/context"
     6     xmlns:tx="http://www.springframework.org/schema/tx"
     7     xmlns:aop="http://www.springframework.org/schema/aop"
     8     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     9        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    10        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    11        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    12     <bean class="com.yuan.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
    13     <bean class="com.yuan.ioc.web.UserAction" id="yyy">
    14       <!-- set注入用property标签 -->
    15       <!-- <property name="userBiz" ref="userBiz"></property> -->
    16       <!-- <property name="uname" value="zs"></property>
    17       <property name="age" value="19"></property> -->
    18       <!-- 构造注入用constructor-arg标签 -->
    19       <constructor-arg name="uname" value="ls"></constructor-arg>
    20       <constructor-arg name="age" value="19"></constructor-arg>
    21       <property name="hobby">
    22         <list>
    23           <value>游戏</value>
    24           <value>听歌</value>
    25           <value>篮球</value>
    26         </list>
    27       </property>
    28     </bean>
    29     
    30     
    31     <bean class="com.yuan.ioc.web.OrderAction" id="xxx">
    32       <!-- <property name="userBiz" ref="userBiz"></property> -->
    33     </bean>
    34     
    35 
    36 </beans>

    1.3、写一个接口

     1 package com.yuan.ioc.biz;
     2 
     3 /**
     4  * 通过企业的案例来讲解使用spring--ioc的必要性
     5  * v1.0 :实现游戏中的上传功能
     6  * v2.0 :对游戏的上传功能进行优化
     7  * 
     8  * ioc的具体体现
     9  * @authorly
    10  *
    11  */
    12 public interface UserBiz {
    13 
    14     public void upload();
    15     
    16 }

      写两个类实现上面的接口

      UserBizImpl1

     1 package com.yuan.ioc.biz.impl;
     2 
     3 import com.yuan.ioc.biz.UserBiz;
     4 
     5 public class UserBizImpl1 implements UserBiz {
     6 
     7     @Override
     8     public void upload() {
     9         System.out.println("实现用户上传的功能");
    10         
    11     }
    12 
    13     
    14 }

    UserBizImpl2

     1 package com.yuan.ioc.biz.impl;
     2 
     3 import com.yuan.ioc.biz.UserBiz;
     4 
     5 public class UserBizImpl2 implements UserBiz {
     6 
     7     @Override
     8     public void upload() {
     9         System.out.println("开始优化性能的代码");
    10         System.out.println("实现用户上传的功能");
    11         
    12     }
    13 
    14     
    15 }

       实体类  UserAction

     1 package com.yuan.ioc.web;
     2 
     3 import java.util.List;
     4 
     5 import com.yuan.ioc.biz.UserBiz;
     6 
     7 /**
     8  * IOC的注入方式及各类类型
     9  *  set注入:
    10  *       基本类型与String  属性uname
    11  *       数组  List<String> hobby
    12  *       自定义类型  userBiz 
    13  *  
    14  *  构造注入
    15  *  自动装配
    16  *      spring4之后出现的
    17  *      byType  根据配置的Bean中的接口,在spring的上下文 
    18  *      byName  根据配置的Bean中的接口名字,在spring的上下文
    19  * 
    20  * 
    21  * @author ly
    22  *
    23  */
    24 public class UserAction {
    25 
    26     private UserBiz userBiz;
    27     private String uname;
    28     private int age;
    29     private List<String> hobby;
    30     
    31     
    32 
    33     public UserAction(String uname, int age) {
    34         super();
    35         this.uname = uname;
    36         this.age = age;
    37     }
    38 
    39     public UserAction() {
    40         super();
    41     }
    42 
    43     public List<String> getHobby() {
    44         return hobby;
    45     }
    46 
    47     public void setHobby(List<String> hobby) {
    48         this.hobby = hobby;
    49     }
    50 
    51     public UserBiz getUserBiz() {
    52         return userBiz;
    53     }
    54 
    55     public void setUserBiz(UserBiz userBiz) {
    56         this.userBiz = userBiz;
    57     }
    58 
    59     public void upload() {
    60         userBiz.upload();
    61     }
    62     
    63     /**
    64      * 注入问题
    65      */
    66     public void test1() {
    67         System.out.println(this.uname);
    68         System.out.println(this.age);
    69         System.out.println(this.hobby);
    70     }
    71     
    72 }

      实体类  OrderAction

     1 package com.yuan.ioc.web;
     2 
     3 import com.yuan.ioc.biz.UserBiz;
     4 
     5 public class OrderAction {
     6 
     7     private UserBiz userBiz;
     8     
     9     public UserBiz getUserBiz() {
    10         return userBiz;
    11     }
    12 
    13     public void setUserBiz(UserBiz userBiz) {
    14         this.userBiz = userBiz;
    15     }
    16 
    17     public void upload() {
    18         userBiz.upload();
    19     }
    20     
    21     
    22 }

       测试类  IocTest

     1 package com.yuan.ioc.test;
     2 
     3 import org.springframework.context.ApplicationContext;
     4 import org.springframework.context.support.ClassPathXmlApplicationContext;
     5 
     6 import com.yuan.ioc.web.OrderAction;
     7 import com.yuan.ioc.web.UserAction;
     8 
     9 public class IocTest {
    10 
    11     public static void main(String[] args) {
    12 
    13         UserAction userAction = new UserAction();
    14         userAction.upload();
    15         
    16     ApplicationContext springContext = new ClassPathXmlApplicationContext("/spring-context.xml");
    17         UserAction userAction = (UserAction) springContext.getBean("yyy");
    18         OrderAction orderAction = (OrderAction) springContext.getBean("xxx");
    19         userAction.upload();
    20         orderAction.upload();
    21         userAction.test1();
    22         
    23     }
    24 
    25 }

        改变spring-context.xml中的配置

    <bean class="com.yuan.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>

      set注入:

     *       基本类型与String  属性uname
     *       数组  List<String> hobby
     *       自定义类型  userBiz

     自动装配:

            spring4之后出现的
     *      byType  根据配置的Bean中的接口,在spring的上下文
     *      byName  根据配置的Bean中的接口名字,在spring的上下文

      自动装配只需要更改是spring-context.xml中的default-autowire="byName"或者default-autowire="byType",然后再依次尝试更改bean中的class和id的值

     2、spring管理整个工程中的JavaBean

     2.1 创建一个监听器  SpringLoaderListenter

     1 package com.yuan.ioc.listener;
     2 
     3 import javax.servlet.ServletContext;
     4 import javax.servlet.ServletContextEvent;
     5 import javax.servlet.ServletContextListener;
     6 import javax.servlet.annotation.WebListener;
     7 
     8 import org.springframework.context.ApplicationContext;
     9 import org.springframework.context.support.ClassPathXmlApplicationContext;
    10 
    11 
    12 /**
    13  * spring 作为管理整个工程中的所有的JavaBean,
    14  *  那么如何在用户发送请求的时候能够访问到指定的JavaBean
    15  *  
    16  *  处理方式:
    17  *       在监听器中将spring的上下文交给tomcat的上下文中进行管理
    18  *       浏览器请求-->request-->servletContext-->springContext-->任意的JavaBean
    19  * @author ly
    20  *
    21  */
    22 @WebListener
    23 public class SpringLoaderListener implements ServletContextListener {
    24 
    25     @Override
    26     public void contextInitialized(ServletContextEvent sce) {
    27         
    28         System.out.println("tomcat一启动就触发了....");
    29         ServletContext tomcatContext = sce.getServletContext();
    30         String springXmlLocation  = tomcatContext.getInitParameter("springXmlLocation");
    31         System.out.println("spring的上下文配置文件"+springXmlLocation);
    32         ApplicationContext springContext =null;
    33         if(springXmlLocation == null || "".equals(springXmlLocation)) {
    34             
    35             springContext = new ClassPathXmlApplicationContext("/spring-context.xml");
    36         }else {
    37             springContext = new ClassPathXmlApplicationContext(springXmlLocation);
    38         }
    39         tomcatContext.setAttribute("spring_key", springContext);
    40         
    41     }
    42     
    43     
    44 }

    2.2 创建servlet  UserServlet

     1 package com.yuan.ioc.web;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.annotation.WebServlet;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 import org.springframework.context.ApplicationContext;
    12 
    13 @WebServlet("/user")
    14 public class UserServlet extends HttpServlet {
    15 
    16     @Override
    17     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    18         doPost(req, resp);
    19     }
    20     
    21     @Override
    22     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    23         System.out.println("处理用户请求");
    24         ApplicationContext springContext = (ApplicationContext) req.getServletContext().getAttribute("spring_key");
    25         UserAction userAction = (UserAction) springContext.getBean("yyy");
    26         userAction.upload();
    27     }
    28     
    29 }

      测试  IocTest

     1 package com.yuan.ioc.test;
     2 
     3 import org.springframework.context.ApplicationContext;
     4 import org.springframework.context.support.ClassPathXmlApplicationContext;
     5 
     6 import com.yuan.ioc.web.OrderAction;
     7 import com.yuan.ioc.web.UserAction;
     8 
     9 public class IocTest {
    10 
    11     public static void main(String[] args) {
    12 
    13 //        UserAction userAction = new UserAction();
    14 //        userAction.upload();
    15         
    16         ApplicationContext springContext = new ClassPathXmlApplicationContext("/spring-context.xml");
    17         UserAction userAction = (UserAction) springContext.getBean("yyy");
    18         OrderAction orderAction = (OrderAction) springContext.getBean("xxx");
    19         userAction.upload();
    20         orderAction.upload();
    21 //        userAction.test1();
    22         
    23     }
    24 
    25 }

    谢谢观看 !!!

  • 相关阅读:
    如何最快速的找到页面某一元素所绑定的点击事件,并查看js代码
    Python3 实现 JS 中 RSA 加密的 NoPadding 模式
    Python实现京东自动登录
    使用Chrome或Fiddler抓取WebSocket包
    python的ws库功能,实时获取服务器ws协议返回的数据
    js遍历对象所有的属性名称和值
    selenium webdriver 实现Canvas画布自动化测试
    CE教程
    How to Get Text inside a Canvas using Webdriver or Protractor
    HTML <​canvas> testing with Selenium and OpenCV
  • 原文地址:https://www.cnblogs.com/ly-0919/p/11336329.html
Copyright © 2020-2023  润新知