User.java
package com.yikuan.vo; public class User { private String name; public User() { System.out.println("user的无参构造方法!"); } public User(String name) { super(); this.name = name; } public void show(){ System.out.println("name:"+name); } }
Test1.java
package com.yikuan.test; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yikuan.vo.User; public class Test1 { public static void main(String[] args) { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); User user = (User) ac.getBean("user"); user.show(); } }
beans.xml配置有3种:
1. 根据参数的下标来设置:
<?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就是java对象,由spring容器来创建和管理 --> <bean id="user" class="com.yikuan.vo.User"> <constructor-arg index="0" value="李四"/> <!-- index指的是构造方法参数的下标 ,从0开始--> </bean> </beans>
2. 根据参数的名称来设置:
<?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就是java对象,由spring容器来创建和管理 --> <!-- bean就是java对象,由spring容器来创建和管理 --> <bean id="user" class="com.yikuan.vo.User"> <!-- name指得是参数名 --> <constructor-arg name="name" value="王五"/> </bean> </beans>
3. 根据参数的类型设置:
<?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就是java对象,由spring容器来创建和管理 --> <!-- bean就是java对象,由spring容器来创建和管理 --> <bean id="user" class="com.yikuan.vo.User"> <constructor-arg type="java.lang.String" value="冯六"/> </bean> </beans>