Spring - Bean管理之配置(@PostConstruct、@PreDestroy、@Scope)
发布日期:2021-06-30 23:47:08 浏览次数:2 分类:技术文章

本文共 1728 字,大约阅读时间需要 5 分钟。

package com.imooc.demo2;import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;@Component("bean1")public class Bean1 {    @PostConstruct    public void init(){        System.out.println("initBean...");    }    public void say(){        System.out.println("say...");    }    @PreDestroy    public void destory(){        System.out.println("destoryBean...");    }}
package com.imooc.demo2;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringDemo2 {    @Test    public void demo1(){        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");        Bean1 bean1 = (Bean1)applicationContext.getBean("bean1");        bean1.say();        applicationContext.close();    }}
运行结果:initBean...say...destoryBean...

package com.imooc.demo2;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;@Component("bean2")@Scope("prototype")public class Bean2 {}
package com.imooc.demo2;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringDemo2 {    @Test    public void demo2(){        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");        Bean2 bean1 = (Bean2)applicationContext.getBean("bean2");        Bean2 bean2 = (Bean2)applicationContext.getBean("bean2");        System.out.println(bean1 == bean2);    }}
运行结果(Ps:默认为单例,所以true):false

Ps:Bean实例化使用XML方式,属性注入用@注解方式。

转载地址:https://lux-sun.blog.csdn.net/article/details/84192696 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Data Structures and Algorithms (English) - 7-28 Review of Programming Contest Rules(30 分)
下一篇:Spring - 属性注入之注解(@Autowired、@Qualifier、@Resource)

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月23日 15时43分17秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章