Spring 学习笔记(二)

Spring学习笔记一中的 test,就是Spring IOC容器中的一个bean对象

在配置文件中配置bean对象


配置形式: 基于XML、基于注解 两种配置形式


配置Bean方式:基于全类名(反射) 、工厂方法、FactoryBean

通过全类名反射的方式在IOC容器中创建Bean实例的话,需要该类里有对应的无参构造函数、


class :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的属性。

每天拨出点时间慢慢学,能学完的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值