Spring 容器加载的三种方式

需要用到的几个类:

1.IUserService :

public interface IUserService {

    public void add();
}

2.UserServiceImpl:

public class UserServiceImpl implements IUserService{

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void add() {
        System.out.println("创建用户...." + name);
    }
}

 

3.beans.xml 文件配置

<?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">

    <bean id="userService" class="com.lkp.service.UserServiceImpl">
        <property name="name" value="summer"></property>
    </bean>
</beans>

 

4.Spring 容器加载的三种方式

第一种:ClassPathXmlApplicationContext ClassPath类路径加载:指的就是classes路径(常用)

     public void test1() {

        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        IUserService userService = (IUserService) context.getBean("userService");
        userService.add();
    }

 

第二种:文件系统路径获得配置文件

    public void test1() {

        ApplicationContext context = new FileSystemXmlApplicationContext("/src/beans.xml");
        IUserService userService = (IUserService) context.getBean("userService");
        userService.add();
    }

 

第三种:使用BeanFactory

    public void test1() {

        String path = "/src/beans.xml";
        BeanFactory factory  = new XmlBeanFactory(new FileSystemResource(path));
        IUserService userService = (IUserService) factory.getBean("userService");
        userService.add();
    }

 

5.BeanFactory和ApplicationContext对比

  • BeanFactory 采取延迟加载,第一次getBean时才会初始化Bean
  • ApplicationContext是对BeanFactory扩展,提供了更多功能

 

  1. 国际化处理
  2. 事件传递
  3. Bean自动装配
  4. 各种不同应用层的Context实现

 6.如何配置一个bean【对象】

spring内部创建对象原理:

  1. 解析xml文件,获取类名,id,属性
  2. 通过反射,用类型创建对象
  3. 给创建的对象赋值 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值