欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring实例化工厂和静态工厂的详细!!

程序员文章站 2024-01-20 16:30:52
...

1.静态/实例工厂

静态工厂:
就是生成实例对象,所有的方法必须是static
实例工厂:
就是先创建类对象,通过对象来调用创建实例对象的方法


静态工厂创建的方法必须是静态方法

2.代码执行:

1.静态

package com.briup.util;

import com.briup.service.UserServiceImpl;
/**
 * 静态方法
 * 静态工厂
 */
public class mybeanfactory {
	
	public static UserServiceImpl getUserService() {
		return new UserServiceImpl();
	}
}

2.非静态

package com.briup.util;

import com.briup.service.UserServiceImpl;
/*
实例工厂
非静态方法
*/
public class mybeanfactory2 {
	public  UserServiceImpl createService() {
		return new UserServiceImpl();
	}
}

3.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="UserService" class="com.briup.util.mybeanfactory" factory-method="getUserService">
</bean>

<!--  测试实例工厂-->
<bean id="mybeanfactory2" class="com.briup.util.mybeanfactory2"></bean>
<bean id="userService2" factory-bean="mybeanfactory2"  factory-method="createService"></bean>

<!-- 测试 factorybean-->
<bean id="factorybean" class="com.briup.util.beanFactoryTest"></bean>
</beans>

4.test文件测试:

!!!

package com.briup.test;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.briup.pojo.User;
import com.briup.service.UserServiceImpl;

public class UserServiceTest {

@Test
	public void  test1() {
		
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean2.xml");
		UserServiceImpl bean = (UserServiceImpl) applicationContext.getBean("userService2");
		//bean.addUser();
		System.out.println(bean);
	}
	
	@Test
	public void test2() {
		
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean2.xml");
		UserServiceImpl u =(UserServiceImpl) applicationContext.getBean("factorybean");
		System.out.println(u);
	}
	@Test
	public void test3() {
		
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean3.xml");
		User u =(User) applicationContext.getBean("UserId");
		System.out.println(u);
	}
	}