spring

Spring

IOC:控制反转,将创建对象权力交给Spring容器,而不是程序员自身去通过new或者反射创建对象。

DI:依赖注入,将属性值注入给属性<property name =“” , value=“”>,将属性注入给bean,<bean id =“” class=“” >,然后再将bean注入给spring容器。

Spring容器有两种:

  • BeanFactory:懒加载,只有在第一次调用getBean()时才会创建对象;
  • ApplicationContext:预加载,在应用启动后就加载所有bean,而且它是继承自BeanFasctory,拥有更多的功能,比如AOP,事件发布与相应(ApplicationEvent),常见的API有ClassPathXmlApplicationContext.
  • 从spring容器获取对象的代码:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Instance instance = (Instance)context.getBean(beanName);

依赖注入的三种方式(底层是通过反射来实现)

1.set方法赋值:基本类型和String–》通过字面值赋值value= “’” ;如果是引用类型,采用ref=“容器中另一个bean的id”

2.构造器注入:通过构造方法赋值,

<bean id = "" , class="">
	<!-- 通过构造方法赋值,下面会根据构造方法的参数和顺序、个数来编写,
	注意要在类中编写对应的构造方法.如果construct-arg的顺序和构造方法的参数顺序不一样,则需要
	通过index, name , type来指定 -->
	<construct-arg value=""  name = ""  type=""></construct-arg>
	<construct-arg value="" name=""  type="" ></construct-arg>
</bean>

3.通过p标签注入:

<bean id="" class=""   p:属性名="value"></bean>

依赖注入集合类型:List,Map,Set,Array等,要通过自己的标签<list> ,<set> , <array>等

<bean id="" class="">
    <!-- 这是对List集合类型赋值 -->
	<property name="list">
		<list>
			<value>xxx</value>
			<value>xxxx<value>
		</list>
	</property>
	<!-- 对map赋值 -->
	<property name="map">
		<map>
			<entry>
				<key>
					<value>xxx</value>
				</key>
				<value>xxxx<value>
			</entry>
		</map>
	</property>

</bean>

特殊值注入问题与自动装配

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值