zoukankan      html  css  js  c++  java
  • IOC、注入

    转:https://blog.csdn.net/lutianfeiml/article/details/51731219  

    实际开发中使用XML还是注解

      • XML:
        • bean管理
      • 注解:
        • 注入属性的时候比较方便
      • 两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入

    Spring支持

    • 构造方法注入
    • setter方法注入

    构造器注入

    • 使用构造方法注入,在Spring配置文件中,通过 <constructor-arg>设置注入的属性 (可以通过index或者type注入)



    setter方法注入

    • 使用setter方法注入,在Spring配置文件中,通过<property>设置注入的属性

    <bean id="car2" class="cn.itcast.spring3.demo5.Car2">
    <!-- <property>标签中name就是属性名称,value是普通属性的值,ref:引用其他的对象 -->
    <property name="name" value="保时捷"/>
    <property name="price" value="5000000"/>
    </bean>
    • 1
    • 2
    • 3
    • 4
    • 5

    setter方法注入对象属性

    • <property>标签中name就是属性名称,value是普通属性的值,ref:引用其他的对象

    名称空间p:注入属性

    • Spring2.5版本引入了名称空间p

      • p:<属性名>="xxx" 引入常量值
      • p:<属性名>-ref="xxx" 引用其它Bean对象
    • 引入名称空间:

      • xmlns:p="http://www.springframework.org/schema/p"
    • xml:

    <bean id="car2" class="cn.itcast.spring3.demo5.Car2" p:name="宝马" p:price="400000"/>
    
    <bean id="person" class="cn.itcast.spring3.demo5.Person" p:name="童童" p:car2-ref="car2"/>
    • 1
    • 2
    • 3

    SpEL:属性的注入

    • Spring3.0提供注入属性方式:
    • 语法:<bean id="" value="#{表达式}">
      • #{'神回复:哈哈'}使用字符串
      • #{topicId3} 使用另一个bean
      • #{topicId4.content.toUpperCase()} 使用指定名属性,并使用方法
      • #{T(java.lang.Math).PI} 使用静态字段或方法
    <bean id="car2" class="cn.itcast.spring3.demo5.Car2">
        <property name="name" value="#{'大众'}"></property>
        <property name="price" value="#{'120000'}"></property>
    </bean>
    
    <bean id="person" class="cn.itcast.spring3.demo5.Person">
        <!--<property name="name" value="#{personInfo.name}"/>-->
    <property name="name" value="#{personInfo.showName()}"/>
        <property name="car2" value="#{car2}"/>
    </bean>
    
    <bean id="personInfo" class="cn.itcast.spring3.demo5.PersonInfo">
        <property name="name" value="张三"/>
    </bean>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    SpEL : 集合属性的注入 – List(数组)

    SpEL : 集合类型属性注入 – Set

    SpEL : 集合类型属性注入 – Map

    SpEL :集合类型属性注入 – Properties

    • 综合案例
        <bean id="collectionBean" class="cn.itcast.spring3.demo6.CollectionBean">
            <!-- 注入List集合 -->
            <property name="list">
                <list>
                    <value>童童</value>
                    <value>小凤</value>
                </list>
            </property>
    
            <!-- 注入set集合 -->
            <property name="set">
                <set>
                    <value>杜宏</value>
                    <value>如花</value>
                </set>
            </property>
    
            <!-- 注入map集合 -->
            <property name="map">
                <map>
                    <entry key="刚刚" value="111"/>
                    <entry key="娇娇" value="333"/>
                </map>
            </property>
    
            <property name="properties">
                <props>
                    <prop key="username">root</prop>
                    <prop key="password">123</prop>
                </props>
            </property>
        </bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    多配置文件的加载

    • 第一种写法:

      • ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml",”bean2.xml”);
    • 第二种方法:

      • <import resource="applicationContext2.xml"/>

    Bean的属性注入–基于注解方式

    IoC容器装配Bean , 基于注解配置方式

    • Spring2.5 引入注解去定义Bean

      • @Component 描述Spring框架中Bean
    • Xml:头文件中加入context路径:xmlns:context=http://www.springframework.org/schema/context

      • 最好直接从dsd-config.html中复制过来相应的代码段
    <?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: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/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- bean definitions here -->
    
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 配置提示操作

      • 将红框中地址复制到Key
    • 引入component-scan标签:<context:component-scan base-package="cn.itcast.spring3"/>,告诉Spring要去扫描哪些包下的类。

    • Spring的框架中提供了与@Component注解等效的三个注解:
      @Repository 用于对DAO实现类进行标注
      @Service 用于对Service实现类进行标注
      @Controller 用于对Controller实现类进行标注
    • 三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强

    自动装配 Bean

    • 使用@Autowired 进行自动注入
    • @Service 标注业务类
    • @Repository 标注DAO
    • @Autowired 默认按照类型进行注入
      • 如果存在两个相同Bean类型,则按照名称注入
      • @Autowired 注入时可以针对成员变量或者setter方法

    • 通过@Autowired的required属性,设置一定要找到匹配的Bean,默认为true,为false时表示对异常不关心。
    • 使用@Qualifier指定注入Bean的名称
      • 使用Qualifier 指定Bean名称后,注解Bean必须指定相同名称
    普通属性
    • @Value(value=”itcast”)
    • private String info;
    对象属性
    • 按类型注入
      • @Autowired:自动装配默认使用类型注入.
    • 按名称进行注入
      • @Autowired 中有一个属性required,默认为true,为false时表示对异常不关心。
      • @Qualifier(“userDao”) 按名称进行注入.

    标准注解@Resource

    • Spring提供对JSR-250中定义@Resource标准注解的支持@Resource@Autowired注解功能相似

    • 下面两个例子等价

    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;
    • 1
    • 2
    • 3
    @Resource(name="userDao")
    private UserDao userDao;
    • 1
    • 2

    Bean其他的属性的配置

    • 配置Bean初始化方法和销毁方法:
      • init-method 和 destroy-method.
      • @PostConstruct : 初始化
      • @PreDestroy : 销毁

    配置Bean的作用范围

    • 使用注解配置的Bean和<bean>配置的一样,默认作用范围都是singleton
      • @Scope注解用于指定Bean的作用范围


    Spring3.0可以 使用Java类提供Bean定义信息

    • Spring3.0以JavaConfig为核心,提供使用Java类定义Bean信息的方法

      • @Configuration 指定POJO类为Spring提供Bean定义信息,代表此类就是一个配置类。
      • @Bean 提供一个Bean定义信息
    • 之前已经通过 component-scan标签 对配置类进行了扫描,故这里不需要再进行手动配置扫描了。

    @Configuration
    public class BeanConfig {
    
        @Bean(name="car")
        public Car showCar(){
            Car car = new Car();
            car.setName("长安");
            car.setPrice(40000d);
            return car;
        }
    
        @Bean(name="product")
        public Product initProduct(){
            Product product = new Product();
            product.setName("空调");
            product.setPrice(3000d);
            return product;
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    实际开发中使用XML还是注解

    • XML:
      • bean管理
    • 注解:
      • 注入属性的时候比较方便
    • 两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入


    Spring整合web开发

    • 正常整合Servlet和Spring没有问题的,但是每次执行Servlet的时候加载Spring配置以及加载Spring环境

    • 解决办法:

      • 将加载的信息内容放到ServletContext中.ServletContext对象是全局的对象。服务器启动的时候创建的,在创建ServletContext的时候就加载Spring的环境。
      • ServletContextListener:用于监听ServletContext对象的创建和销毁的.
      • 以上解决方法可以通过导入Spring web开发jar包来解决 : spring-web-3.2.0.RELEASE.jar

    web.xml中的配置

    • 将Spring容器初始化,交由web容器负责
    • 配置核心监听器 ContextLoaderListener
    • 配置全局参数contextConfigLocation
      • 用于指定Spring的框架的配置文件位置(因为:applicationContext.xml文件与默认位置不一致)

    <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    
    </listener>
     <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:applicationContext.xml</param-value>
     </context-param>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    获得WebApplicationContext对象

    • 因为Spring容器已经交由web容器初始化和管理,获得WebApplicationContext对象,需要依赖ServletContext对象 通常在Servlet中完成:
    WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    • 1
    • 另一种方式
    WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    • 1
    • eg:

    • web.xml

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
      <display-name></display-name>
     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
    
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
     </context-param>
    
      <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>cn.itcast.servlet.UserServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    • UserServlet & UserService
    public class UserServlet extends HttpServlet {
    
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /*ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");*/
            WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    
            UserService userService = (UserService) applicationContext
                    .getBean("userService");
            userService.sayHello();
        }
    
    
    
    public class UserService {
    
        public void sayHello(){
            System.out.println("Hello Spring web...");
        }
    }

  • 相关阅读:
    [转]WM_COMMAND消息
    [转]DELPHI之关于String的内存分配
    [转]我们永远优雅,但绝不炫耀:合并BPL包图文教程!
    [转]AS400
    [转]Delphi中变体记录及存储方式
    [转]WaitForMultipleObject与MsgWaitForMultipleObjects用法
    [转]delphi中的HWnd,THandle,HDC有什么区别
    [转]Delphi使用FireBird嵌入式版本发布方法
    [转]如何使用Delphi设计强大的服务器程序
    Oracle递归查询
  • 原文地址:https://www.cnblogs.com/zhanglijun/p/9083662.html
Copyright © 2011-2022 走看看