使用ioc创建对象的方式之一(通过无参的构造方法来创建:)
通过无参的构造方法来创建:
User.java
1 package com.yikuan.vo; 2 3 public class User { 4 public User() { 5 System.out.println("user的无参构造方法!"); 6 } 7 private String name; 8 public void setName(String name) { 9 this.name = name; 10 } 11 public void show(){ 12 System.out.println("name:"+name); 13 } 14 }
beans.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就是java对象,由spring容器来创建和管理 --> <bean id="user" class="com.yikuan.vo.User"> <property name="name" value="张三"></property> </bean> </beans>
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(); } }