第一种 设置注入
<bean id="emp0" class="com.bean.Employee" >
<!--第一种 -->
<property name="name" value="李智恩"></property>
<property name="age" value="24"></property>
</bean>
第二种 键值分开
<bean id="emp1" class="com.bean.Employee" >
<property name="name" >
<value>李智恩</value>
</property>
<property name="age">
<value>24</value>
</property>
</bean>
测试类
@Test
public void creatSpring(){
//需要通过一个类来加载spring的配置
String resource = "Spring.xml";
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(resource);
//换了一种方式赋值相当于上面的set方法
Employee emp=(Employee) ac.getBean("emp1");
System.out.println(emp);
}
第三种 构造器注入
<bean id="emp2" class="com.bean.Employee" >
<constructor-arg name="name" value="李智恩"></constructor-arg>
<constructor-arg name="age" value="25"></constructor-arg>
</bean>
bean类
public Employee(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public Employee() {
}
第四种 数组下标
<!--第四种 -->
<bean id="emp3" class="com.bean.Employee" >
<constructor-arg index="0" value="胡歌"></constructor-arg>
<constructor-arg index="1" value="25"></constructor-arg>
</bean>
测试类
@Test
public void creatSpring2(){
String resource = "Spring.xml";
ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext(resource);
Object bean = cs.getBean("emp3");
System.out.println(bean);
}
注意:名字需要和配置文档名字一致。