applicationContext.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--bean可以定义多个名称,使用name属性完成-->
<!--<bean id="userService" name="userService1,userService2" class="com.itheima.service.impl.UserServiceImpl"/>-->
<!--scope用于控制bean创建后的对象是否为单列-->
<!--<bean id="userService3" scope="prototype" class="com.itheima.service.impl.UserServiceImpl"/>-->
<!--init-method和destroy-method用于控制bean的生命周期-->
<!-- <bean id="userService3" scope="singleton" init-method="init" destroy-method="destroy" class="com.itheima.service.impl.UserServiceImpl"/>-->
<!--静态工厂创建bean-->
<bean id="userService4" class="com.itheima.service.UserServiceFactory" factory-method="getService"/>
<!--实例工厂对应的bean-->
<bean id="factoryBean" class="com.itheima.service.UserServiceFactory2"/>
<!--实例工厂创建北bean,依赖工厂对象对应的bean-->
<bean id="userService5" factory-bean="factoryBean" factory-method="getService"/>
</beans>
package com.itheima.service;
import com.itheima.service.impl.UserServiceImpl;
public class UserServiceFactory {
public static UserService getService(){
System.out.println("factory create object....");
return new UserServiceImpl();
}
}
package com.itheima.service;
import com.itheima.service.impl.UserServiceImpl;
public class UserServiceFactory2 {
public UserService getService(){
System.out.println("instance factory create object....");
return new UserServiceImpl();
}
}
import com.itheima.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserApp {
public static void main(String[] args) {
//2.加载配置文件
/*ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//3.获取资源
UserService userService1 = (UserService) ctx.getBean("userService3");
UserService userService2 = (UserService) ctx.getBean("userService3");
UserService userService3 = (UserService) ctx.getBean("userService3");
System.out.println(userService1);
System.out.println(userService2);
System.out.println(userService2);*/
//userService.save();
/* ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//3.获取资源
UserService userService1 = (UserService) ctx.getBean("userService3");
UserService userService2 = (UserService) ctx.getBean("userService3");
UserService userService3 = (UserService) ctx.getBean("userService3");
ctx.close();*/
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//3.获取资源
UserService userService1 = (UserService) ctx.getBean("userService5");
userService1.save();
}
}