javascript
Spring文档学习
Spring文档学习
参考Spring Framework Documentation学习
1. IoC 容器
1.1 容器实例化
<beans><import resource="services.xml"/><import resource="resources/messageSource.xml"/><import resource="/resources/themeSource.xml"/><bean id="bean1" class="..."/><bean id="bean2" class="..."/> </beans>注意:这里不建议resource那里使用classpath:URL的写法,因为运行时解决进程会选择最近的classpath根,然后查找它的父文件夹。类路径配置的改变可能会导致错误的路径,找不到对应的资源。
1.2 使用容器
ApplicationContext是高级工厂的接口,能够维护不同bean及其依赖项的注册表。
获取实例:
ApplicationContext T getBean(String name, Class<T> requiredType)
最灵活的变种是GenericApplicationContext与reader相结合(如XmlBeanDefinitionReader)
使用:
GenericApplicationContext context = new GenericApplicationContext(); new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml"); context.refresh();1.3 Bean Overview
在容器内,bean对象表示为BeanDefinition,其中包含以下元数据:
- 包限定的类名:通常情况是bean的实现类
- Bean行为配置元素,指明bean在容器中如何表现,像scope,生命周期回调等等
- 引用其他bean(称为合作者或依赖)
- 新创建的对象里设置其他配置
BeanDefinition有以下属性:
| Name |
| Scope |
| Constructor arguments |
| Properties |
| Autowiring mode |
| Lazy initialization mode |
| Initialization method |
| Destruction Method |
ApplicationContext允许由用户创建的对象的注册,通过ApplicationContext的getBeanFactory()方法返回DefaultListableBeanFactory。通过这个BeanFactory的registerSingleton()和registerBeanDefinition()方法。
需要ASAP注册Bean元数据和手动提供的单例实例,以便容器在自动装配(auto wire)和其他内省步骤期间正确推理它们。
1.3.1 Naming Beans
Bean命名约定:小写字母开头,驼峰命名。
Spring扫描时,对那些没有命名的bean生成名字,遵循以下原则:采用simple class name,首字母小写。但是特殊情况下,如果有多个字符,并且第一和第二个字母都是大写,则原有的写法会被保留。
当有多个系统的时候,简单的使用xml-based 即可完成别名操作。
1.3.2 实例化beans
bean定义实际上是创建一个或多个对象的配方。
class属性的两种使用方式:
内部类的话,class属性需要写二进制代码名,如:com.example.SomeThing$OtherThing
利用构造函数实例化
However, depending on what type of IoC you use for that specific bean, you may need a default (empty) constructor.
利用静态工厂方法实例化
如:
<bean id="clientService"class="examples.ClientService"factory-method="createInstance"/>利用对象工厂方法实例化
例如:
<!-- the factory bean, which contains a method called createInstance() --> <bean id="serviceLocator" class="examples.DefaultServiceLocator"><!-- inject any dependencies required by this locator bean --> </bean><!-- the bean to be created via the factory bean --> <bean id="clientService"factory-bean="serviceLocator"factory-method="createClientServiceInstance"/>注意:一个工厂类也可以包含多个工厂方法
这种方法表明工厂bean本身可以通过依赖注入(DI)进行管理和配置
转载于:https://www.cnblogs.com/studentytj/p/10639780.html
总结
以上是生活随笔为你收集整理的Spring文档学习的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: django xadmin 1不在可用的
- 下一篇: 原生JavaScript实战之搜索框筛选