spring-静态工厂

实例化有三种方法:

1.默认构造
2.静态工厂(用于生成实例对象,所有方法必须是 static)

<bean id = "" class="静态工厂包名+类名" factory-method="静态方法名">

3.实例工厂

静态工厂

在配置文件中将工厂类里的方法实例化
一、工厂

package com.sj.staticFactory;

import com.sj.service.UserService;
import com.sj.service.UserServiceImpl;


public class staticFactory {
	public static UserService addUser() {
		
		return  new UserServiceImpl();
		
	}
}

二、spring配置

<?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-4.1.xsd">
	<bean id="userService" class="com.sj.staticFactory.staticFactory" factory-method="addUser"></bean>
</beans>

三、接口和实现类
userService

package com.sj.service;

public interface UserService {

	void addUser();

}

userServiceImpl

package com.sj.service;

public class UserServiceImpl implements UserService {
	
	@Override
	public void addUser() {
		System.out.println("addUser");
	}
}

四、测试(输出是addUser)

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

import com.sj.service.UserService;

public class MyTest {
@Test
	public void test() {
		String xmlPath = "ApplicationContext.xml";
		ApplicationContext applicationContext= new ClassPathXmlApplicationContext(xmlPath);
		UserService userService = applicationContext.getBean("userService",UserService.class);
		userService.addUser();
		
	}
}

五、结果

十一月 26, 2019 6:35:13 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6d9c638: startup date [Tue Nov 26 18:35:13 GMT+08:00 2019]; root of context hierarchy
十一月 26, 2019 6:35:13 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [ApplicationContext.xml]
addUser

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值