JavaWeb学习笔记-spring-02-ioc-BeanFactory&ApplicationContext

BeanFactory&ApplicationContext

BeanFactory://ioc容器,面向spring本身
ApplicationContext//应用上下文(spring容器),面向开发者

BeanFactory

Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Test test = (Test)factory.getBean("test");

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC 
    "-//SPRING//DTD BEAN//EN"
    "http://www.spring framework.org/dtd/spring-beans.dtd">
<benas>
    <bena id="test" class="com.mr.test.Test">
</beans>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
public class Car {
    private String brand;
    private String color;
    private String maxSpeed;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(String maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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="car" class="com.smart.Car"
            p:brand="xxx"
            p:color="xxx"
            p:maxSpeed="xxx"/>

</beans>
public class BeanFactoryTest {
    public static void main(String[] args)throws Throwable{
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource res = resolver.getResource("classpath:beans.xml");
        BeanFactory bf = new XmlBeanFactory(res);
        System.out.println("init BeanFactory");
        Car car = bf.getBean("car",Car.class);
        System.out.println(car.getColor());
    }
}

ApplicationContext

//"classpath:beans.xml"=="beans.xml",配置文件在类路径下
ApplicationContext ctx = new ClassPathXmlApplicationoContext("beans.xml");
//"file:beans.xml"=="beans.xml",配置文件在文件系统下
ApplicationContext ctx = new FileSystemXmlApplicationContext("beans.xml");
//多个配置文件组合
ApplicationCntext ctx = new ClassPathXmlApplicationContext(new String[]{"beans1.xml","beans2.xml"});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值