spring创建对象的几种方式

spring创建对象的几种方式

Spring 通过容器(bean工厂),创建对象和属性。

对象是由spring容器创建的,对象属性是spring容器设置的。这个过程就叫控制反转:

控制的内容:指谁来控制对象的创建,传统的应用程序对象的创建是由程序本身控制的,使用spring后,是由spring来创建对象的。
反转:正转指程序来创建对象,反转指程序本身不去创建对象,而变为被打接收对象。

总结:以前对象是由程序本身来创建,使用spring后,程序变为被动接收spring创建好的对象。
  控制反转--等同于-依赖注入(dependency injection) 


第一种:调用无参构造器创建。

1、创建vo类

public class Hello {
	private String name;
	
	public Hello(){
		System.out.println("无参构造创建");
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void show(){
		System.out.println("name:"+name);
	}
}

2、编写beans.xml




	
		
	

3、测试

blic class Test {
	public static void main(String[] args) {
		//解析beans.xml,生产管理相应的bean对象
		ApplicationContext conte
t = new ClassPathXmlApplicationContext("beans.xml");
		//调用getBean()方法,会创建一个对象,通过无参构造方法创建。
		Hello hello = (Hello)context.getBean("hello");
		hello.show();
	}
二、调用有参构造器,创建对象。
1、创建vo类

public class Hello {
	private String name;
	
	public Hello(String name){
		System.out.println("调用有参构造器!");
		this.name = name;
	}
	
	public void show(){
		System.out.println("name:"+name);
	}
}

2、编写beans.xml




	
		
				
		
		
		
	
		
		
	


3、测试

public class Test {
	public static void main(String[] args) {
		//解析beans.xml,生产管理相应的bean对象
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		//调用getBean()方法,会创建一个对象,通过有参构造方法创建。
		Hello hello = (Hello)context.getBean("hello");
		hello.show();
	}
}

三、通过工厂方法创建对象

第一种:静态工厂

1、创建工厂类

package spring.Factory;

import spring.bean.User;

public class UserFactory {
	public static User getUser(String name){
		return new User(name);
	}
}

2.编写bean.xml

	
		
	
3、测试

public class Test {
	public static void main(String[] args) {
		//解析beans.xml,生产管理相应的bean对象
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		//调用getBean()方法,会创建一个对象,通过工厂创建。
		User hello = (User)context.getBean("user");
		hello.show();
	}
}
第二种:动态工厂

1、创建动态工厂类

package spring.Factory;

import spring.bean.User;

public class UserDynamicFactory {
	public User getUser(String name){
		return new User(name);
	}
}
2、编写beans.xml


	
		
	








你可能感兴趣的:(spring)