IoC创建对象的方式
使用无参构造创建对象,默认
pojo
package com.wx.pojo;
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);
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.wx.pojo.User">
<property name="name" value="wx"/>
</bean>
</beans>
测试
import com.wx.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
User user = new User();
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user2 = (User) context.getBean("user");
user2.show();
}
}
输出
使用有参构造创建方式
- 使用下标赋值
<?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="user" class="com.wx.pojo.User">
<!--下标赋值-->
<constructor-arg index="0" value="wx"/>
</bean>
</beans>
测试
import com.wx.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
user.show();
}
}
2. 使用参数类型赋值
<!--第二种方式,通过类型创建-->
<bean id="user" class="com.wx.pojo.User">
<constructor-arg type="java.lang.String" value="wx"/>
</bean>
测试
3. 通过参数名
<bean id="user" class="com.wx.pojo.User">
<constructor-arg name="name" value="wx"/>
</bean>
测试