<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- ###############对象创建############### -->
<!-- 1. 默认无参数构造器
<bean id="user1" class="cn.itcast.b_create_obj.User"></bean>
-->
<!-- 2. 带参数构造器 -->
<bean id="user2" class="cn.itcast.b_create_obj.User">
<constructor-arg index="0" type="int" value="100"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" value="Jack"></constructor-arg>
</bean>
<!-- 定义一个字符串,值是"Jack" ; String s = new String("jack")-->
<bean id="str" class="java.lang.String">
<constructor-arg value="Jacks"></constructor-arg>
</bean>
<bean id="user3" class="cn.itcast.b_create_obj.User">
<constructor-arg index="0" type="int" value="100"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" ref="str"></constructor-arg>
</bean>
<!-- 3. 工厂类创建对象 -->
<!-- # 3.1 工厂类,实例方法 -->
<!-- 先创建工厂 -->
<bean id="factory" class="cn.itcast.b_create_obj.ObjectFactory"></bean>
<!-- 在创建user对象,用factory方的实例方法 -->
<bean id="user4" factory-bean="factory" factory-method="getInstance"></bean>
<!-- # 3.2 工厂类: 静态方法 -->
<!--
class 指定的就是工厂类型
factory-method 一定是工厂里面的“静态方法”
-->
<bean id="user" class="cn.itcast.b_create_obj.ObjectFactory" factory-method="getStaticInstance"></bean>
<!-- 对象写法 -->
<!--
问题:spring配置文件中,bean节点的id与name属性的区别?
id 不能有特殊符号, 且唯一,且不能以数字开始
name 可以有特殊符号
-->
<bean id="test" name="1test" class="cn.itcast.b_create_obj.User"></bean>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="user1" class="cn.itcast.cproperty.user">
<constructor-arg value="100"></constructor-arg> //给对象赋值
<constructor-arg value="tom"></constructor-arg>
</bean>
public class app {
private ApplicationContext ac= new ClassPathXmlApplicationContext("cn/itcast/cproperty/bean.xml");
@Test
public void testset() throws Exception{
user user=(user)ac.getBean("user1"); //这里使用的是 bean.xml 中的id值
System.out.println(user);
}
}
<bean id="user1" class="cn.itcast.cproperty.user">
<property name="id" value="101"></property>
<property name="name" value="lilei"></property>
</bean> //使用 user类中的属性来赋值 前提需要 get,set方法。