zoukankan      html  css  js  c++  java
  • 03-spring_配置bean

    <?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">
    	<!--  配置bean -->
    	<bean id="helloworld" class="com.demo.beans.HelloWorld">
    		<property name="name" value="Spring"></property>
    	</bean>
    
    </beans>
    

    <!-- 配置bean

      class : bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有无参数的构造器

          id:标识容器中的bean,id唯一

    -->

    在SpringIOC容器读取Bean配置创建Bean实例之前,必须对他进行实例化,只有在容器实例化后,才能从IOC容器中获取Bean实例并使用。

    Spring提供了两种类型的IOC容器实现

    ----BeanFactory IOC容器的基本实现

    ----ApplicationContext提供了更多的高级特性,是BeanFactory的子接口

    前者是Spring框架的基础设置,面向Spring本身;

    后者是面向使用Spring框架的开发者,几乎所有的应用场合都使用后者,而非前者。

    ApplicationContext的主要实现类:

    ----ClassPathXmlApplicationContext : 从类基路径下加载配置文件

    ----FileSystemXmlApplicationContext : 从文件系统中加载配置文件

    ConfigurableApplicationContext扩展于ApplicationContext,新增两个主要方法:

    refresh()和close(),让ApplicationContext具有启动,刷新和关闭上下文的能力

    ApplicationContext在初始化上下文时就实例化所有单利bean

    WebApplicationContext是专门为WEB应用而准备 ,它允许从相对于WEB根目录的路径中完成初始化工作

    依赖注入(属性注入,构造器注入,工厂方法模式注入)

    属性注入:就是<property name="username" value="jim"/>

    构造器注入:

    使用构造器注入属性值可以指定参数的位置和参数的类型(可混用),以区分重载的构造器。

    Car.java

    package com.demo.beans;
    
    public class Car {
    	private String brand;
    	private String corp;
    	private int price;
    	private int maxspeed;
    
    	public Car(String brand, String corp, int price) {
    		this.brand= brand;
    		this.corp = corp;
    		this.price = price;
    				
    	}
    	
    	@Override
    	public String toString() {
    		return this.brand+this.price;
    	}
    }
    

      

    <bean id="car" class="com.demo.beans.Car">
    		<constructor-arg value="Audi"></constructor-arg>
    		<constructor-arg value="Shanghai"></constructor-arg>
    		<constructor-arg value="10000"></constructor-arg>
    		<!-- <constructor-arg value="10000" index="2"></constructor-arg> -->
    		<!-- <constructor-arg value="10000" type="int"></constructor-arg> -->
    	</bean>
    

      

  • 相关阅读:
    QT学习笔记
    局域网摄像头安装与调试
    从0开始搭建视觉检测智能车
    树莓派安装anaconda
    手把手教你搭建视觉检测智能车
    树莓派与Arduino串口通信实验
    树莓派设置关机重启键
    树莓派can通信
    树莓派GPIO使用笔记
    MySQL练习题
  • 原文地址:https://www.cnblogs.com/boucher/p/5738246.html
Copyright © 2011-2022 走看看