bean.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" 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="随意名称" class="包名.类名"></bean> <!-- 2. 带参数构造器 --> <bean id="随意名称" class="包名.类名"> <constructor-arg index="索引" type="类型" value="值"></constructor-arg> <constructor-arg index="1" type="java.lang.String" value="Jack"></constructor-arg> </bean> <!-- 定义一个字符串,值是"Jack" ; String s = new String("jack")--> <bean id="引用名称" class="java.lang.String"> <constructor-arg value="Jacks"></constructor-arg> </bean> <bean id="随意名称" class="c包名.类名"> <constructor-arg index="0" type="int" value="100"></constructor-arg> <constructor-arg index="1" type="java.lang.String" ref="引用名称"></constructor-arg> </bean> <!-- 3. 工厂类创建对象 --> <!-- # 3.1 工厂类,实例方法 --> <!-- 先创建工厂 --> <bean id="工厂" class="包名.工厂类名"></bean> <!-- 在创建user对象,用factory方的实例方法 --> <bean id="随意名称" factory-bean="工厂" factory-method="工厂类里的方法名"></bean> <!-- # 3.2 工厂类: 静态方法 --> <bean id="随意名称" class="包名.工厂类名" factory-method="工厂类里的方法名(静态方法)"></bean> <!-- 对象写法 --> <!-- ###############对象属性赋值############### --> <!-- 1) 通过构造函数 --> <bean id="随意名称" class="包名.类名"> <constructor-arg index="索引" type="类型" value="值"></constructor-arg> <constructor-arg index="1" type="java.lang.String" value="Jack"></constructor-arg> </bean> <!-- 2) 通过set方法给属性注入值 --> <bean id="随意名称" class="c包名.类名" scope="prototype"> <!-- 类里面要写好set方法 --> <property name="id" value="101"></property> <property name="name" value="Jack"></property> </bean> <!-- 3) 通过p名称空间注入值 --> <bean id="user" class="cn.itcast.c_property.User" p:name="Jack0001"></bean> <!-- ###############小案例############### --> <!-- 1.ref引用创建类 --> <!-- dao instance --> <bean id="userDao" class="包名.UserDao"></bean> <!-- service instance --> <bean id="userService" class="包名.UserService"> <property name="userDao" ref="userDao"></property> </bean> <!-- action instance --> <bean id="userAction1" class="包名.UserAction"> <property name="userService" ref="userService"></property> </bean> <!-- 2.内部bean创建类 --> <bean id="userAction2" class="包名.UserAction"> <property name="userService"> <bean class="包名.UserService"> <property name="userDao"> <bean class="包名.UserDao"></bean> </property> </bean> </property> </bean> <!-- 3.p 名称空间创建类 --> <bean id="userDao" class="cn.itcast.c_property.UserDao"></bean> <bean id="userService" class="cn.itcast.c_property.UserService" p:userDao-ref="userDao"></bean> <bean id="userAction" class="cn.itcast.c_property.UserAction" p:userService-ref="userService"></bean> </beans>
时间: 2024-10-12 01:25:10