IOC配置-bean的生命周期控制

 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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值