《Spring 2.0 技术手册》读书笔记四-非XML的Bean定义文件配置
2010-11-14 16:43
453 查看
上篇文章详细介绍了基于XML的Bean定义文件的常用配置方式,本文简单介绍不用xml文件来定义Bean的两种方法:.properties文件,程序配置Bean。但是个人觉得spring就是由于使用xml来配置Bean,才使得开发简单,表述强大,所以没有必要再使用其他方式。但也不忽略个别特殊情况,可能使用这两种方式比xml配置要更适合。所以简单了解如下。
.properties配置
可以新建一个文件如beans-config.properties
“helloBean”即为Bean的别名设置,.(class)用于指定类源。像其他.(abstract)、.(parent)、.(lazy-init)、.(singleton)等,都可以用来设置相关属性。.helloWord,为HelloBean的属性名。要是引用已存在的实例,可以为.helloWord(ref)。其他的就不再详解。
读取.properties文件的代码如下:
输出结果应该就是beans-config.properties文件指定的"Weclome Spring Properties!"。
代码配置
不用任何文件来定义Bean,全在代码中设置属性和Bean间的依赖关系,如下:
输出结果应为"Welcome Spring NoConfig!"。
这两种Bean配置方式,都较为复杂、不易阅读。稍微了解即可。
.properties配置
可以新建一个文件如beans-config.properties
helloBean.(class)=HelloBean helloBean.helloWord=Weclome Spring Properties!
“helloBean”即为Bean的别名设置,.(class)用于指定类源。像其他.(abstract)、.(parent)、.(lazy-init)、.(singleton)等,都可以用来设置相关属性。.helloWord,为HelloBean的属性名。要是引用已存在的实例,可以为.helloWord(ref)。其他的就不再详解。
读取.properties文件的代码如下:
BeanDefinitionRegistry reg= new DefaultListableBeanFactory(); PropertiesBeanDefinitionReader reader= new PropertiesBeanDefinitionReader(reg); reader.loadBeanDefinitions( new ClassPathResource("beans-config.properties")); BeanFactory factory = (BeanFactory)reg; HelloBean hello=(HelloBean)factory.getBean("helloBean"); System.out.println(hello.getHelloWord());
输出结果应该就是beans-config.properties文件指定的"Weclome Spring Properties!"。
代码配置
不用任何文件来定义Bean,全在代码中设置属性和Bean间的依赖关系,如下:
MutablePropertyValues properties= new MutablePropertyValues(); properties.add("helloWord", "Welcome Spring NoConfig!"); //设置Bean RootBeanDefinition definition= new RootBeanDefinition(HelloBean.class,properties); //注册Bean定义与Bean别名 BeanDefinitionRegistry reg= new DefaultListableBeanFactory(); reg.registerBeanDefinition("helloBean", definition); BeanFactory factory=(BeanFactory)reg; HelloBean hello=(HelloBean)factory.getBean("helloBean"); System.out.println(hello.getHelloWord());
输出结果应为"Welcome Spring NoConfig!"。
这两种Bean配置方式,都较为复杂、不易阅读。稍微了解即可。
相关文章推荐
- 《Spring 2.0 技术手册》读书笔记四-非XML的Bean定义文件配置
- spring 实例化定义在xml配置文件中的bean的三种方法?
- 搭建SSH框架遇到的struts.xml找不到spring定义的bean的错误(配置文件的路径问题)
- ssh项目中,对于spring的bean.xml和web.xml文件的基本配置
- web.xml中定义的Spring的XML配置文件启动顺序
- Spring Bean定义总结:配置文件手写Bean PK 组建扫描用注解
- spring xml 配置文件向Bean 设置List值
- Spring的xml配置文件的定义
- spring中读取xml配置文件、获取bean的几种方式
- 通过DefaultListableBeanFactory加载.xml配置文件学习Spring-IoC容器注册/加载bean的机制(源码走读)
- Spring读取xml配置文件并加载bean对象
- 在Maven项目中加载spring中的bean的配置xml文件会提示找不到解决方法
- Spring-配置文件Bean定义中parent属性详解
- 译--Spring中 bean定义profiles的使用 javaConfig 和XML配置
- Spring的xml配置bean文件原理-[Java反射机制]
- spring源码解析-从xml配置文件中获取bean
- Spring根据XML配置文件注入属性 其实也是造bean,看看是使用constructor还是setter顺带完成属性赋值
- spring引用不同的xml配置文件中的bean
- 通过上下文路径得到在spring配置文件中所定义的bean
- spring BeanFactory加载xml配置文件示例