zoukankan      html  css  js  c++  java
  • spring的基本使用bean的实例化方式与属性注入两种方法

    IOC

    配置文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <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 
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    	<!-- ioc入门 -->
    	<bean id="userService" class="com.shi.service.UserService"></bean>
    </beans>

    测试代码:

    package com.shi.service;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class UserServiceTest {
    
    	@Before
    	public void setUp() throws Exception {
    	}
    
    	@Test
    public void test() {
    	//1 加载spring配置文件,根据创建对象
    	ApplicationContext applicationContext=
    	new ClassPathXmlApplicationContext("classpath:spring/applicationContext-service.xml");
    	//2 获取容器中创建的对象
    	UserService userService=(UserService) applicationContext.getBean("userService");
    	UserService userService2=(UserService) applicationContext.getBean("userService");
    	System.out.println(userService);
    	System.out.println(userService2);//俩次获取的是同一个对象
    	userService.add();
    }
    
    }

    配置文件没有提示的问题:

    创建对象三种方法

    静态工厂类

    package com.shi.bean;
    
    /*
     * 使用静态类工厂创建bean2对象
     */
    public class Bean2Factory {
    	
        public static Bean2 getBean2(){
    	return new Bean2();
        }
    }

    applicationContext.xml文件中的配置:

    <!-- 使用静态工厂创建对象 -->
    <bean id="ben2Factory" class="com.shi.bean.Bean2Factory" 
        factory-method="getBean2"></bean>

    实例工厂类

    package com.shi.bean;
    
    /*
     * 使用实例工厂类创建bean3对象
     */
    public class Bean3Factory {
    	
    	public  Bean3 getBean3(){
    		return new Bean3();
    	}
    }

    applicationContext.xml文件中的配置:

    <!-- 使用实例工厂创建对象 -->
    <!-- 先创建工厂对象 -->
    <bean id="bean3Factory" class="com.shi.bean.Bean3Factory"></bean>
    <bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>

    bean 标签的常用属性

    属性注入

        注意:这里说的注入方式是手动的注入方式,而我们常用的注入方式为自动注入即注解的方式(可以进一步分为按类型注入与按名称注入)

    IOC 和 DI

    spring 整合 web 项目

     
     
     
     

    本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

  • 相关阅读:
    HDU3746 Cyclic Nacklace KMP
    KMP的小结
    POJ1916 Period KMP
    POJ 2406 Power Strings 简单KMP模板 strcmp
    HDU 2157 How many ways?? (邻接矩阵快速幂)
    (VIJOS) VOJ 1067 Warcraft III 守望者的烦恼 矩阵快速幂
    puppet之自定义fact(转载)
    Shell标准输出、标准错误 >/dev/null 2>&1
    如何在linux中用命令产生一个范围内的随机数?
    SNMP协议
  • 原文地址:https://www.cnblogs.com/chaojibaidu/p/12685019.html
Copyright © 2011-2022 走看看