如何配置Bean

来源:互联网 发布:直播间源码下载 编辑:程序博客网 时间:2024/05/18 00:07

配置Bean

-配置形式:基于XML文件的方式;

-Bean的配置方式:通过全类名(反射)

-IOC容器BeanFactory&ApplicationContext

-依赖注入的方式:属性注入;构造器注入


ApplicationContext.xml文件

<!--      通过setter方法来配置bean属性      class:bean的全类名,通过反射的方式在IOC容器中建立Bean。所以要求Bean中必须有无参的构造器      id:标识容器中的bean,id唯一--><bean id="helloworld" class="">     <property name="name"  value="Spring"></property></bean><!--      通过构造方法来配置bean属性  --><bean id="XXX" class="">     <constructor-arg value="" index="0" ></constructor-arg>     <constructor-arg value="" index="1"></constructor-arg>       <constructor-arg value="" index="2"></constructor-arg></bean><!--使用构造器注入属性值可以指定参数的位置和参数的类型以区分重载的构造器!--><pre name="code" class="html"><bean id="XXX" class="">     <constructor-arg value="" type="java.lang.String" ></constructor-arg>      <constructor-arg value="" type="java.lang.String"></constructor-arg>       <constructor-arg value="" type="java.lang.double"></constructor-arg>
</bean>

Spring提供了两种类型的IOC容器实现。

-BeanFactory:IOC容器的基本实现。

-ApplicationContext:提供了更多的高级特性是BeanFactory的子接口。

-BeanFactory是Spring框架的基础设施,面向Spring本身;

 ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合都直接使用ApplicationContext而非底层的BeanFactory

-无论使用何种形式,配置文件是相同的。

Main.java

//1.创建Spring的IOC容器对象//ApplicationContext代表容器,实际上是一个接口//ClassPathxmlApplicationContext是ApplicationContext接口的实现类,该实现类从类路径下来加载配置文件ApplicationContext ctx = new ClassPathxmlApplicationContext("applicationContext.xml");//2.从IOC容器中获取Bean实例//利用id定位到IOC容器的BeanHelloWorld helloworld =(HelloWorld) ctx.getBean("helloWorld");//利用类型返回IOC容器中的Bean,但要求IOC容器中必须只用有一个该类型的Bean//HelloWorld helloworld =(HelloWorld) ctx.getBean("HelloWorld.class");Car car = (Car) ctx.betBean("XXX");//3.调用HelloWorld类中的方法




0 0