一 配置Bean元素
<bean name="user" class="cn.hd.test.User" id="user" scope="prototype"></bean>
ApplicationContext.xml文件中配置bean元素,属性解释
name:属性,自己起个名字,没有限制
class:类的相对路径
id:命名方式唯一,里面不能出现特殊字符,比如“/*action”就不可以,也可以不写
scope:对象的创建方式,里面有两个属性单例模式(singleton)和多例模式(prototype),默认为单例模式
单例模式和多例模式会在另一边博客上详细解释
二spring创建对象的方式
(1)无参的构造函数创建
public User() {
System.out.println("调用了无参构造函数");
}
(2)静态工厂实例化
public class UserFactory { |
applicationContext.xml配置文件
<bean name="userFactory" class="cn.hd.test.UserFactory" factory-method="createUser"></bean>
并且创建一个UserFactory该类中提供一个静态的createUser方法
(3)实例化工厂创建
//实例化工厂创建
public User createUser1(){
System.out.println("实例化工厂创建方式");
return new User();
}
<bean name="userFactory1" class="cn.hd.test.UserFactory"></bean>
<bean name="user1" factory-bean="userFactory1" factory-method="createUser1"></bean>
三对象属性的注入
(1)set注入
<bean name="car" class="cn.hd.injection.Car">
<property name="name" value="法拉利" ></property>
<property name="color" value="red"></property>
</bean>
name为类属性名 value属性值
基本属性有8大数据类型+String,引入属性 对象
<bean name="user" class="cn.hd.injection.User"> |
name为类的属性值,value为属性值 ref为引用的bean类的name
(2)构造函数注入
Name value(ref) index type 属性 具体的值 参数的位置 参数的类型 |
(3)p空间注入(最简单)但是业界不认可可以自己开发用,大部分人还是使用<property>
,
<bean name="user5" class="cn.hd.injection.User" |
用p空间注入还必须导入约束,不然会报错
xmlns:p="http://www.springframework.org/schema/p" http://www.springframework.org/schema/p |
(4)spel注入(这个注入有点类似于El和OGNL表达式)
|
(5)复杂类型的注入
数组(List/set/map/properties)等类型注入,先来看第一个注入方式
①数组注入
<bean name="collectionBean" class="cn.hd.injection.CollectionBean"> 如果有多个用array包裹,如果有引用用ref |
@Test CollectionBean collectionBean = (CollectionBean) ac.getBean("collectionBean"); |
至于结果你们可以自己演示一下,上面是applicationContext.xml文件配置,以及测试代码
②list注入
<!--<property name="list" value="1"></property>--> |
CollectionBean collectionBean1 = (CollectionBean) ac.getBean("collectionBean"); |
③map注入
map注入是以键值对key key-ref(引入方式) value value-ref 方式注入
<property name="map">
|
CollectionBean collectionBean2 = (CollectionBean) ac.getBean("collectionBean"); |
④properties注入
<property name="properties">
|
CollectionBean collectionBean3 = (CollectionBean) ac.getBean("collectionBean"); |
以上的注入方式都是可以测试的,下面是测试的结果不完全
注入方式说完就给大家说一个模块化小知识,很简单的就是在在applicationContext.xml文件导入其他类的applicationContext.xml文件。就相当于struts2文件。就是直接在applicationContext.xml文件中添加以下代码就可以了
<import resource="classpath:applicationContext.xml" ></import> |