核心:ioc创建对象的方式
方法一:通过无参构造方法创建对象
示例:
ServiceImp.class
package serviceimp;
import service.Service;
import userdao.UserDao;
import userdaoimp.UserDaoImp;
public class ServiceImp implements Service{
public ServiceImp(){
System.out.println("无参构造方法创建对象");
}
private UserDao userdaoimp=null;
public void setUserDao(UserDao userdaoimp){
this.userdaoimp=userdaoimp;
}
public void getUser(){
userdaoimp.getUser();
}
其他地方和spring03相同
方法二 :通过(有参构造方法——参数下标法)创建对象
package cn.vo;
public class User {
private String name;
public User(String name){
this.name=name;
System.out.println("有参构造方法创建对象");
}
public void show(){
System.out.println("UserName:"+name);
}
}
beans.xml
<bean id="user" class="cn.vo.User">
<constructor-arg index="0" value="zhangsan"></constructor-arg>
</bean>
测试代码:Test.java
package cn.vo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
User user=(User)ac.getBean("user");
user.show();
}
}
}
方法二 :通过(有参构造方法——参数类型)创建对象
配置文件修改内容如下:
<bean id="user" class="cn.sxt.vo.User">
<constructor-arg type="java.lang.String" value="zhangsan"></constructor-arg>
</bean>
方法二 :通过(有参构造方法——参数名)创建对象
<bean id="user" class="cn.sxt.vo.User">
<constructor-arg name="name" value="zhangsan"></constructor-arg>
<!-- 前边的name是指后边要写的是参数名,如果参数名为age,那么后边的name变为age -->
</bean>
方法三、工厂方法——静态工厂
<bean id="user" class="cn.sxt.userfactory.UserFactory" factory-method="NewInstance">
<constructor-arg index="0" value="zhangsan"></constructor-arg>
</bean>
方法三、工厂方法——动态工厂
benas.xml配置如下:
<bean id="userDynamicFactory" class="cn.userfactory.UserDynamicFactory">
</bean>
<bean id="user" class="cn.userfactory.UserDynamicFactory" factory-method="NewInstance">
<constructor-arg index="0" value="zhangsan"></constructor-arg>
</bean>