一句话翻译时间到了!
最不可或缺的是IOC容器,紧随其后的是AOP。顺便集成了AspectJ 作为其补充。
1.IOC容器
1.1 IOC容器和bean。
将本应由对象自身管理的依赖由容器管理,这就是DI,BeanFactory
提供了IOC容器的基本功能,作为子类的ApplicationContext
完全继承了BeanFactory
的功能并完善了。bean是由容器生成、构造、管理的对象。
1.2容器总览
接口ApplicationContext
也就是IOC容器,通过读XML,注解、代码获取Bean原数据,然后生成、注册、管理bean。如图:
XML、注解/JAVA代码是三大元数据注册方法,XML中通常使用<bean>标签表示需要管理的bean,JAVA代码则是@Bean注解:
<bean id="..." class="...">
id用于区分独立的bean,class通常是全名,用于表示bean类型。
初始化容器:
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
引入其他xml中的bean配置:
<beans>
<import resource="services.xml"/>
使用容器:
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
尽管上面的getBean方法可以直接从容器中取得bean,但是在实践中我们并不应该使用这个方法也不需要使用这个方法,这也保证了我们的代码不必与Spring紧耦合。
1.3 bean总览
spring管理bean通过元数据配置,元数据配置应有一下几种:
Property | Explained in… |
---|---|
class | |
name | |
scope | |
constructor arguments | |
properties | |
autowiring mode | |
lazy-initialization mode | |
initialization method | |
destruction method |
容器也允许将管理外的bean注册到容器中,使用registerBeanDefinition方法。
1.3.1 id与name
id唯一且不能含特殊字符,name反之。未定义id与name时,包含类的全名即为name;
Spring3.1之后id的类型也是xsd:string了.
如果想要用ref引用bean,必须声明name。