V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
JohnZorn
V2EX  ›  Java

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

  •  
  •   JohnZorn · Jan 23, 2018 · 2089 views
    This topic created in 3028 days ago, the information mentioned may be changed or developed.

    跟着视频看的 实现 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 replies    2018-01-24 19:58:24 +08:00
    JohnZorn
        1
    JohnZorn  
    OP
       Jan 24, 2018 via Android
    dd 有没大哥说一下呀 一天了还是没想通。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3106 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:35 · PVG 11:35 · LAX 20:35 · JFK 23:35
    ♥ Do have faith in what you're doing.