使用Bean创建对象:
在applicationContext.xml中
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="people" class="com.spring.pojo.People"/> </beans>
测试:(读取applicationContext.xml时就已经创建类)
public class Test { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); People people = applicationContext.getBean("people",People.class); System.out.println(people); } }
有参构造:
<bean id="people" class="com.spring.pojo.People"> <constructor-arg name="id" index="0" value="1"></constructor-arg> <constructor-arg name="name" index="1" value="spring"></constructor-arg> </bean>
使用工厂设计模式创建对象:
1.静态工厂:(不需要new一个工厂对象)
工厂类:
public class PeopleFactory { public static People instancePeople() { return new People(); } }
配置bean:
<!-- 静态工厂 --> <bean id="people3" class="com.spring.pojo.PeopleFactory" factory-method="instancePeople"></bean>
1.实例工厂:(需要new一个工厂对象)
工厂类:
public class PeopleFactory {
public People instancePeople() {
return new People();
}
}
配置bean:
<!-- 实例工厂 --> <bean id="peopleFactory" class="com.spring.pojo.PeopleFactory"></bean> <bean id="people2" factory-bean="peopleFactory" factory-method="instancePeople"></bean>
在配置文件中给Bean对象的属性赋值:
<bean id="people1" class="com.spring.pojo.People"> <property name="id"> <value>123</value> </property> <property name="name"> <value>springName</value> </property> </bean>
等价写法:
<bean id="people1" class="com.spring.pojo.People"> <property name="id" value="123"></property> <property name="name" value="spring"></property> </bean>
spring内部使用了类的无参构造器和setXxx方法
<property>内各种标签示例:set,array,map,props(java.util.properties)....
<property name="sets"> <set> <value>1</value> <value>2</value> <value>3</value> </set> </property> <property name="strs"> <array> <value>1</value> <value>2</value> <value>3</value> </array> </property> <property name="map"> <map> <entry key="a" value="1"></entry> <entry key="b" value="2"></entry> <entry key="c" value="3"></entry> </map> </property> <property name="desk"> <ref bean="desk" /> </property> <property name="pros"> <props> <prop key="a">1</prop> </props> </property>
DI ( 依赖注入,一个对象中包含另一个对象):在property中使用ref
<property name="desk"> <ref bean="desk" /> </property> ------------------------------------------------- <bean id="desk" class="com.spring.pojo.Desk"> <property name="id"> <value>1</value> </property> <property name="name"> <value>desk</value> </property> </bean>