如何配置Bean
配置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容器的Bean HelloWorld helloworld =(HelloWorld) ctx.getBean("helloWorld"); //利用类型返回IOC容器中的Bean,但要求IOC容器中必须只用有一个该类型的Bean //HelloWorld helloworld =(HelloWorld) ctx.getBean("HelloWorld.class"); Car car = (Car) ctx.betBean("XXX"); //3.调用HelloWorld类中的方法
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: Scala Seq示例
- 下一篇: scala Map 和 Tuple操作