Spring-Bean学习笔记

什么是Spring中的Bean

  • 如果把Spring看作一个大工厂,则Spring容器中的Bean就是该工厂的产品。使用时需在配置文件中告诉需要哪些Bean,以及用何种方式将这些Bean装配在一起。Bean的本质就是java中的类,而Spring中的Bean就是对实体类的引用,来生产java类对象。
    在这里插入图片描述

Bean的作用域

在这里插入图片描述

  • singleton作用域
<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-2.5.xsd">
	<bean id="命名" class="权限类全名" scope="sinleton"/>
  • prototype作用域
<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-2.5.xsd">
	<bean id="命名" class="权限类全名" scope="prototype"/>

基于XMl的配置

在这里插入图片描述

  • 构造方式注入方式装配User案例

    <bean id="user1" class="权限类的全名">
    	<constructor-arg index="0" value="tom" />    
        <constructor-arg index="1" value="123" />  
    </bean>
    
  • 使用设值注入方式配置User案例

<bean id="user1" class="权限类的全名">
	<property name="username" value="tom" />    
    <property name="password" value="123" />  
</bean>

基于Annotation(注解)的装配

在这里插入图片描述

  • XMl文件的配置
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	<!--使用context空间,通知Spring扫描指定包下所有的Bean类,进行注解解析-->
    <context:component-scan base-package="需要对注解进行解析的包全名" />
 

自动装配

在这里插入图片描述

  • 自动装配事例
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	<bean id="userDao" class="类的接口全名"></bean>
    <bean id="userSevice" class="类的接口全名" autowire="byName"></bean>
    <bean id="userController" class="类的全名" autowire="byName"></bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值