V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
choice4
V2EX  ›  Java

spring 中设置作用域为 prototype 和实现 ApplicationContextAware 接口会冲突吗

  •  
  •   choice4 · 2018-01-23 19:27:40 +08:00 · 1626 次点击
    这是一个创建于 2276 天前的主题,其中的信息可能已经有所发展或是发生改变。

    跟着视频看的 实现 ApplicationContextAware 接口后通过方法 的参数获取 Bean 还有一个 JUnit 的测试类应该是 ClassPathXmlApplicationContext 对象 getBean

    @Before
    public void before() {
        if (StringUtils.isEmpty(springXmlpath)) {
            springXmlpath = "classpath*:spring-*.xml";
        }
        try {
            context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
            context.start();
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
    
    @After
    public void after() {
        context.destroy();
    }
    
    @SuppressWarnings("unchecked")
    protected <T extends Object> T getBean(String beanId) {
        try {
            return (T)context.getBean(beanId);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    这个类是 UnitTestbase JUnit4 测试类继承了它 在 @Test 的方法下是 super.getBean("xml 中 Bean 的 id")

    然后就抛异常是空指针 但是如果作用域是单例就没事 单元测试方法可以运行 实现 ApplicationContextAware 接口后实现的方法也可以运行 但是如果作用域改为 prototype 就会异常两个方法里面的方法体都不会执行 如果把单元测试方法体代码注释掉则不会抛出异常 但是实现接口的方法也不会执行

    如果需要代码我再补

    1 条回复    2018-01-24 19:58:24 +08:00
    choice4
        1
    choice4  
    OP
       2018-01-24 19:58:24 +08:00 via Android
    dd 有没大哥说一下呀 一天了还是没想通。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4584 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:06 · PVG 12:06 · LAX 21:06 · JFK 00:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.