Bean的作用域
一共有6种,但是后面的四种是基于web应用的;
| Scope | Description |
|---|---|
| singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
| prototype | Scopes a single bean definition to any number of object instances. |
| request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. |
| session | Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. |
| application | Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext. |
| websocket | Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext. |
测试代码:
1 | ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml"); |
1.sigleton:无论创建几个都始终只有一个并且是默认的作用域
1 | <bean id="student" class="com.saxon.pojo.Student" c:name="saxon" scope="singleton"> |
结果:true
2.prototype:每次创建都会新建一个对象,就是浪费资源
1 | <bean id="student" class="com.saxon.pojo.Student" c:name="saxon" scope="prototype"> |
结果:false;
八、自动装配
1.显示自动装配 xml 装配
applicationContext.xml
2.Java文件自动装配
3.隐式自动装配
autowrite:
1.autowire=”byName”
它会自动寻找我们属性中还没有注入的属性,选取ID 为setXXX的XXX 自动装配
比如:
1 | public void setAddress (Address address) { |
1 | <bean id="address" class="com.saxon.pojo.Address"> |
这个的set后缀就是address,那么就去找ID为address的bean;如果ID不一致就不会自动装配;区分大小写,id唯一;
2.autowire=”byType”
会自动寻找我们属性中还没有注入的属性,选取类的类型为setXXX的XXX 自动装配
1 | public void setAddress (Address address) { |
1 | <bean id="address" class="com.saxon.pojo.Address"> |
com.saxon.pojo.Address类型唯一自动装配,于id无关;id可以不写;



