Spring IOC创建对象的方式
-
使用无参构造创建对象,默认方式!
实体类
public class User { private String name; public User() { System.out.println("进入了User的无参构造"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public void show(){ System.out.println("name:"+name); } }
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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.abin.pojo.User"> <property name="name" value="abin"/> </bean> </beans>
测试
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); User user = (User) context.getBean("user"); user.show(); }
输出结果
进入了User的无参构造 name:abin
通过结果可以看出,user对象是通过无参构造方法创建的
-
也可也使用有参构造创建对象