Spirng IoC/DI容器 的helloworld工程2-多个配置文件
2017-02-14 15:24
417 查看
实际开发可以多人参与,一个模块对应一个配置文件
配置文件applicationContext.xml中
配置文件applicationContext-user.xml中
配置文件applicationContext-dep.xml中
1.读取多个配置文件
1.如果多个配置文件中有name相同的bean,按照ClassPathXmlApplicationContext()装载顺序,后面的bean回覆盖前面的bean,所以bean的命名要规范,bean命名前加上模块名
2.读取一次xml,也就是执行ClassPathXmlApplicationContext()方法,并不会创建一个IoC容器的实例。
所以一次装载所有配置文件,节约资源
如下
证明对象被创建几次,可以在构造函数中输出一句话
如下
配置文件的内容
1.全限定类名的配置
2.行为的配置
3.参数的配置
4.关系的配置
bean的名称:按照java的变量命名,因为
Bean的别名,和name一样用
容器实例化bean的技术:反射
方法1.通过构造器
配置文件applicationContext.xml中
<!-- 配置公共的bean -->
配置文件applicationContext-user.xml中
<import resource="applicationContext.xml"/> <bean name="user-test" class="cn.javass.spring3.hello.ImplOne"></bean>
配置文件applicationContext-dep.xml中
<bean name="dep-test" class="cn.javass.spring3.hello.ImplTwo"></bean>
1.读取多个配置文件
public class Client { public static void main(String[] args) { // 第一步:读配置文件,来创建ApplicationContext,相当于bean的工厂 ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml", "applicationContext-user.xml", "applicationContext-dep.xml" }); // 第二步:获取需要操作的bean Api api = (Api) context.getBean("dep-test"); ////////// 第三步:以下和spring就没有关系了,面向接口编程//////////// String s = api.t(21); System.out.println("s==" + s); // 打印要有前缀 } }
1.如果多个配置文件中有name相同的bean,按照ClassPathXmlApplicationContext()装载顺序,后面的bean回覆盖前面的bean,所以bean的命名要规范,bean命名前加上模块名
2.读取一次xml,也就是执行ClassPathXmlApplicationContext()方法,并不会创建一个IoC容器的实例。
所以一次装载所有配置文件,节约资源
如下
//不创建bean容器 ApplicationContext context2 = new ClassPathXmlApplicationContext(new String[] { "applicationContext-user.xml", "applicationContext-dep.xml" }); Api apis = (Api) context2.getBean("dep-test"); //创建bean容器
证明对象被创建几次,可以在构造函数中输出一句话
如下
public class ImplOne implements Api { public ImplOne() { // 每次创建一个对象,会执行一次 System.out.println("oneooooooooo"); } @Override public String t(int a) { // TODO Auto-generated method stub System.out.println("now in Impl One t,a==" + a); return "hello==" + a; } }
配置文件的内容
1.全限定类名的配置
2.行为的配置
3.参数的配置
4.关系的配置
bean的名称:按照java的变量命名,因为
<!--相当于Api api = new ImplOne();--> <bean name="test" class="cn.javass.spring3.hello.ImplOne"></bean>
Bean的别名,和name一样用
<bean name="dep-test" class="cn.javass.spring3.hello.ImplOne"></bean> <!--给上述bean设置别名cc--> <alias name="dep-test" alias="cc"></alias>
容器实例化bean的技术:反射
方法1.通过构造器
<bean name="dep-test" class="cn.javass.spring3.hello.ImplOne"></bean>
相关文章推荐
- JavaBean和Map转换封装类的方法
- Spring Bean基本管理实例详解
- Spring中多配置文件及引用其他bean的方式
- 解析Java中如何获取Spring中配置的bean
- Java中BEAN与EJB的区别浅析
- 深入解析Java的Spring框架中bean的依赖注入
- Spring Bean的生命周期详细介绍
- 浅谈spring容器中bean的初始化
- Java中Spring获取bean方法小结
- 详解Spring Boot 使用Java代码创建Bean并注册到Spring中
- 详解Java的Spring框架中bean的定义以及生命周期
- 详解Java的Spring框架中bean的注入集合
- Java的Spring框架中bean的继承与内部bean的注入
- Java类获取Spring中bean的5种方式
- 各种概念POJO、JAVABEAN、DAO、DTO、PO、VO、BO、SSH、EJB
- 让Spring Controller 的方法基本数据类型参数支持Bean Validation
- 图文教程:使用MyEclipse的hibernate工具从数据库反向生成实体Bean
- JSR 303 - Bean Validation 介绍及最佳实践
- 领域驱动之无状态操作
- Spring Bean自动装配