实例化有三种方法:
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