Spring学习笔记一中的 test,就是Spring IOC容器中的一个bean对象
在配置文件中配置bean对象
配置形式: 基于XML、基于注解 两种配置形式
通过全类名反射的方式在IOC容器中创建Bean实例的话,需要该类里有对应的无参构造函数、
id:标识容器中的bean id 唯一
容器实例化
在 SpringIOC 容器读取Bean创建Bean实例之前,必须对它进行实例化,即容器实例化Spring提供两种方式实现:
1.BeanFactory:IOC容器的基本实现,面向Spring本身,是框架基础设施
2.ApplicationContext,是BeanFactory的子接口,面向开发者,基本所有常用都是直接使用这个
ApplicationContext的主要实现类:
1.ClassPathXml 该实现类从类路径加载配置文件,比较常用的形式
2.FileSystemXml 才文件路径加载
<span style="font-size:12px;">ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-autowire.xml");</span>
Spring注入
Spring注入方式: 属性注入,构造器注入,工厂方法注入(使用很少)
属性注入,通过setter方法,属性注入使用元素property。是最常用的注入方式
构造方法注入:通过构造器注入,使用元素constructor-arg,使用构造器注入的这种方式的前提是该类有对应的构造函数
例子:两种方式,test是通过属性注入,car是通过构造器注入
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!--
<bean id = "test" class="com.harry.spring.learning.User">
<property name="username" value="huanghong"></property>
<property name="password" value="harrysir"></property>
</bean>
-->
<!-- 使用构造器注入属性值,可指定参数的位置和类型以区分重载的构造器 -->
<bean id="car" class="com.harry.spring.learning.Car">
<constructor-arg value="Audi" index="0"></constructor-arg>
<constructor-arg value="300000" type="int"></constructor-arg>
<constructor-arg value="shenzhen" type = "java.lang.String" ></constructor-arg>
</bean>
</beans>
package com.harry.spring.learning;
public class Car {
private String brand;
private int price;
private int maxSpeed;
private String corp;
//构造器,初始化了三个属性
public Car(String brand, int price, String corp) {
super();
this.brand = brand;
this.price = price;
this.corp = corp;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + ", maxSpeed="
+ maxSpeed + ", corp=" + corp + "]";
}
}
Car的话只初始化了三个属性,所以对应的配置文件里也没有配置maxSpeedz的属性。
每天拨出点时间慢慢学,能学完的