Spring创建容器对象

来源:互联网 发布:腾讯足球数据统计 编辑:程序博客网 时间:2024/05/22 13:03

1.Spring常用的容器
ClassPathXmlApplicationContext:从类加载路径下搜索配置文件,并根据配置文件创建Spring容器对象。
FileSystemXmlApplicationContext:从文件系统相对路径或绝对路径下去搜索配置文件,并根据配置文件创建Spring容器对象。
AnnotationConfigApplicationContext:从一个或多个基于Java的配置类中加载Spring应用上下文。

2.实例代码演示package com.learnSpring02;public class Axe {    public String chop(){        return"使用斧头砍柴";    }}package com.learnSpring02;public class Person {    private Axe axe;    //在setter中注入axe对象    public void setAxe(Axe axe) {        this.axe = axe;    }    public void useAxe(){        System.out.println("我打算去砍点柴");        //调用axe对象的 chop方法,表明person对象依赖于axe对象        System.out.println(axe.chop());    }}package com.learnSpring02;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class test {    @SuppressWarnings("resource")    @Test    public void test(){        ApplicationContext context=new ClassPathXmlApplicationContext("test.xml");        //Person p = (Person) context.getBean("person");        //使用getBean(String name,Class<T>requiredType)无需转换类型        Person p=context.getBean("person",Person.class);        p.useAxe();    }}<?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="helloworld"  class="com.learn.Spring01.HelloWorld">     <property   name ="name"  value="Javas2"/>   </bean></beans>控制台输出结果:我打算去砍点柴使用斧头砍柴

总结:
Spring获取Bean对象的常用两种方法如下:
1.Object getBean(String id):根据容器中bean的id来获取一个指定的bean,获取bean之后需要类型强制转换。
2.T getBean(String id,ClassrequiredType):直接的到相要的对象,无需强制转换。

原创粉丝点击