Spring装配bean基于XML,注解

一、装配Bean基于XML

1、实例化方式

(1)3种bean实例化方式:默认构造,静态工厂,实例工厂
(2)默认构造<bean id="" class=""> <!--必须提供默认构造-->

(3)静态工厂

  • 常用与spring整合其他框架(工具)
  • 静态工厂:用于生成实例对象,所有的方法必须是static
<bean id=""  class="工厂全限定类名"  factory-method="静态方法">
  • 工厂代码
public class MyBeanFactory {

    /**
     * 创建实例
     * @return
     */
    public static UserService createService(){
        return new UserServiceImpl();
    }
}
  • spring配置
<!-- 将静态工厂创建的实例交予spring 
        class 确定静态工厂全限定类名
        factory-method 确定静态方法名
    -->
    <bean id="userServiceId" class="com.itheima.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>

(4)实例工厂

  • 实例工厂:必须先有工厂实例对象,通过实例对象创建对象。提供所有的方法都是“非静态”的。
  • 工厂代码
public class MyBeanFactory {

    /**
     * 创建实例
     * @return
     */
    public UserService createService(){
        return new UserServiceImpl();
    }

}
  • spring配置
<!-- 创建工厂实例 -->
    <bean id="myBeanFactoryId" class="com.itheima.c_inject.c_factory.MyBeanFactory"></bean>
    <!-- 获得userservice 
        * factory-bean 确定工厂实例
        * factory-method 确定普通方法
    -->
    <bean id="userServiceId" factory-bean="myBeanFactoryId" factory-method="createService"></bean>

2、Bean种类

(1)普通bean:之前操作的都是普通bean。 ,spring直接创建A实例,并返回
(2)FactoryBean:是一个特殊的bean,具有工厂生成对象能力,只能生成特定的对象。

  • BeanFactory 和 FactoryBean 对比?
  • BeanFactory:工厂,用于生成任意bean。
  • FactoryBean:特殊bean,用于生成另一个特定的bean。例如:ProxyFactoryBean ,此工厂bean用于生产代理。 获得代理对象实例。AOP使用

3、作用域

(1)作用域:用于确定spring创建bean实例个数
这里写图片描述

(2)取值:

  • singleton 单例,默认值
  • prototype多例,每执行一次getBean将获得一个实例。例如:struts整合spring,配置action多例

4、生命周期

(1)目标方法执行前后执行后,将进行初始化或销毁

<bean id="" class="" init-method="初始化方法名称"  destroy-method="销毁的方法名称">

(2)目标类

public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("e_lifecycle add user");
    }

    public void myInit(){
        System.out.println("初始化");
    }
    public void myDestroy(){
        System.out.println("销毁");
    }

}

(3)spring配置

<!--  
        init-method 用于配置初始化方法,准备数据等
        destroy-method 用于配置销毁方法,清理资源等
    -->
    <bean id="userServiceId" class="com.itheima.e_lifecycle.UserServiceImpl" 
        init-method="myInit" destroy-method="myDestroy" ></bean>

(4)测试

public void demo02() throws Exception{
        //spring 工厂
        String xmlPath = "com/itheima/e_lifecycle/beans.xml";
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        UserService userService = (UserService) applicationContext.getBean("userServiceId");
        userService.addUser();

        //要求:1.容器必须close,销毁方法执行; 2.必须是单例的
//applicationContext.getClass().getMethod("close").invoke(applicationContext);
        // * 此方法接口中没有定义,实现类提供
        applicationContext.close();

    }

5、属性依赖注入

(1)构造方法

  • 目标类
public class User {

    private Integer uid;
    private String username;
    private Integer age;

    public User(Integer uid, String username) {
        super();
        this.uid = uid;
        this.username = username;
    }

    public User(String username, Integer age) {
        super();
        this.username = username;
        this.age = age;
    }
  • spring配置
<!-- 构造方法注入 
        <constructor-arg> 用于配置构造方法一个参数argument
            name :参数的名称
            value:设置普通数据
            ref:引用数据,一般是另一个bean id值

            index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。
            type :确定参数类型
        例如:使用名称name
            <constructor-arg name="username" value="jack"></constructor-arg>
            <constructor-arg name="age" value="18"></constructor-arg>
        例如2:【类型type 和  索引 index
            <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
            <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>-->


<bean id="userId" class="com.itheima.f_xml.a_constructor.User" >
        <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
        <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>
    </bean>

(2)setter方法

  • spring配置
<!-- setter方法注入 
         普通数据 
            <property name="" value="值">
            等效
            <property name="">
                <value>值
         引用数据
            <property name="" ref="另一个bean">
            等效
            <property name="">
                <ref bean="另一个bean"/>
    -->
    <bean id="personId" class="com.itheima.f_xml.b_setter.Person">
        <property name="pname" value="张三"></property>
        <property name="age">
            <value>1234</value>
        </property>

        <property name="homeAddr" ref="homeAddrId"></property>
        <property name="companyAddr">
            <ref bean="companyAddrId"/>
        </property>
    </bean>

    <bean id="homeAddrId" class="com.itheima.f_xml.b_setter.Address">
        <property name="addr" value="江西"></property>
        <property name="tel" value="911"></property>
    </bean>
    <bean id="companyAddrId" class="com.itheima.f_xml.b_setter.Address">
        <property name="addr" value="北京八宝山"></property>
        <property name="tel" value="120"></property>
    </bean>

(3)集合注入

<!-- 
        集合的注入都是给<property>添加子标签
            数组:<array>
            List:<list>
            Set:<set>
            Map:<map> ,map存放k/v 键值对,使用<entry>描述
            Properties:<props>  <prop key=""></prop>  【】

        普通数据:<value>
        引用数据:<ref>
    -->
    <bean id="collDataId" class="com.itheima.f_xml.e_coll.CollData" >
        <property name="arrayData">
            <array>
                <value>张三</value>
                <value>李四</value>
                <value>王五</value>
            </array>
        </property>

        <property name="listData">
            <list>
                <value>你1</value>
                <value>你2</value>
                <value>你3</value>
                <value>你4</value>
            </list>
        </property>

        <property name="setData">
            <set>
                <value>停封</value>
                <value>薄纸</value>
                <value>关系</value>
            </set>
        </property>

        <property name="mapData">
            <map>
                <entry key="jack" value="杰克"></entry>
                <entry>
                    <key><value>tom</value></key>
                    <value>汤姆</value>
                </entry>
            </map>
        </property>

        <property name="propsData">
            <props>
                <prop key="你">ni</prop>
                <prop key="我">wo</prop>
                <prop key="他">ta</prop>
            </props>
        </property>
    </bean>

二、装配Bean基于注解

1、注解

(1)注解:就是一个类,使用@注解名称;开发中使用注解取代xml配置文件

2、web开发注解

(1)@Component取代<bean class="">
(2)@Component(“id”) 取代<bean id="" class="">
(3)web开发,提供3个@Component注解衍生注解(功能一样)取代<bean class="">

  • @Repository :dao层
  • @Service:service层
  • @Controller:web层

3、依赖注入注解

(1)依赖注入,给私有字段设置,也可以给setter方法设置
(2)普通值:@Value(“”)
(3)引用值:

  • 方式1:按照【类型】注入 @Autowired
  • 方式2:按照【名称】注入 @Autowired @Qualifier(“名称”)
  • 方式3:按照【名称】注入 @Resource(“名称”)

4、生命周期注解

(1)初始化:@PostConstruct
(2)销毁:@PreDestroy

5、作用域注解

(1)@Scope(“prototype”) 多例

6、使用注解前提

(1)注解使用前提,添加命名空间,让spring扫描含有注解类
这里写图片描述
(2)代码

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 组件扫描,扫描含有注解的类 -->
    <context:component-scan base-package="com.itheima.g_annotation.a_ioc"></context:component-scan>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值