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"/>
</beans>
package com.itheima.service.impl;
import com.itheima.service.UserService;
public class UserServiceImpl implements UserService {
public UserServiceImpl() {
System.out.println("constructor is running.....");
}
public void init(){
System.out.println("init.....");
}
public void destroy(){
System.out.println("destrory.....");
}
public void save() {
System.out.println("user Service running......");
}
}
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();
}
}