3.Spring-XML配置

68 阅读1分钟

1、在Spring中,注入对象的方式有三种

第一种是使用XML的形式注入对象

第二种是使用Java注解的形式

第三种是包扫描

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">

<!-- 可以直接向Spring 容器中注册Bean     -->
    <bean class="org.luckyboy.demo.model.User" id="user"/>
    <bean class="org.luckyboy.demo.model.User" id="user1">
        <constructor-arg name="id" value="1"/>
        <constructor-arg name="name" value="shangsan"/>
        <constructor-arg name="address" value="深圳"/>
    </bean>
</beans>

上图的user1是通过构造器的方式给对象赋值

也可以通过get、set方法给对象赋值

<bean class="org.luckyboy.demo.model.User" id="user">
    <property name="address" value="guangzhou"/>
</bean>

创建容器

package org.luckyboy.demo.model;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo1 {
    public static void main(String[] args) {
        //创建Spring容器
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationcontext.xml");
    }
}

容器在构建过程中,Bean就已经被创建了 ctx.getBean()这个方法就是跟容器去要一个Bean,将来无论是通过何种方式跟容器要一个Bean,底层实现都是这个方法

ctx.getBean("根据名字获取Bean,返回Object,返回之后需要强转")

ctx.getBean("根据类型获取,这个要求该容器中只存在一个实例"),多个会报错。根据类型去获取,首先是根据类型查找beanname,找到名字之后,再调用ctx.getBean("beanname")去获取bean。

在bean生成时,也可以在xml文件中配置使用的初始化方法和销毁时调用的方法 或者在对象实现接口,重写对应的方法即可。

public class User implements InitializingBean, DisposableBean{
    private Integer id;
    private String name;
    private String address;
    
    @Override
    public void destroy() throws Exception {

    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }