spring框架中工厂方法的创建和销毁

1.编写接口UserSerivce:

public interface UserService {

    public void sayHello();
}

2.编写实实现接口的方法,在该方法中除了要实现接口中的方法,还定义了inti和destory方法:

public class UserServiceImpl implements UserService{

    private String name;
    
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public void sayHello() {
        System.out.println("sayHello!"+name);
        
    }
    public void init(){
        System.out.println("对象被创建了");
    }
    public void destory(){
        System.out.println("对象被销毁了");
    }
}

3.配置applicationContext.xml。在bean标签中加入destory-method,以及init-method属性:

<bean id="userService" class="com.huida.demo2.UserServiceImpl" destroy-method="destory" init-method="init">
</bean>

4.在demo.java中创建工厂,实现方法的调用。

@Test
    public void run5(){
        //创建工厂,加载核心配置文件
        ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");//加载配置文件的时候,对象就已经创建了
        //从工厂中获取对象
        UserService usi=(UserService) ac.getBean("userService");
        //调用方法
        usi.sayHello();
        //关闭工厂,工厂关闭,对象都会销毁
        ac.close();
    }

5.执行结果为:

猜你喜欢

转载自www.cnblogs.com/wyhluckdog/p/10126814.html