0

我有一个使用旧 spring.jar (1.2.6) 的项目,从这个项目中,我预计会调用一个较新版本 (spring version 5.0.7) spring boot 项目的方法。以下是我在旧版本项目中创建 bean 的方式。

创建 Autowired bean 时出现 NullPointer 异常。

从 XML 创建 bean:spring test-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "qvc-spring-beans.dtd">
<beans>
<bean name="testPci" class="com.test.client.TestPci">
</bean>
</beans>

示例父上下文.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans SYSTEM "spring-beans.dtd">

<beans> 
        
    <import resource="classpath:/com/test/test-context.xml" />
    <bean id="classA" class="com.test.A" >      
        <property name="testPci">
            <ref bean="testPci"/>
        </property>
    </bean>
</beans>

Java代码旧spring项目:

package com.test;
public class A{

private TestPci testPci;

private ApplicationContext ctx;

public TestPci getTestService() {
        if (!StringUtils.isValid(ctx)) {
            ctx = new ClassPathXmlApplicationContext("./com/test/test-context.xml");
            
        }

        if (!StringUtils.isValid(this.testPci)) {
            if (StringUtils.isValid(ctx)) {
                testPci = (TestPci) ctx.getBean("testPci");
                TestPci testPci = (TestPci) ctx
                        .getBean("testPci");
                this.setSecureTestService(testPci);
            }
        }
        return this.getSecureTestService();
    }
    
     public TestPci getSecureTestService() {
        return testPci;
    }

    public void setSecureTestService(TestPci testPci) {
        this.testPci = testPci;
    }
    
public void methodA(){
//Calling newer code form old spring code:
testPci.testing("1", "2", "3");
}
    
    }

像上面一样调用“TestPci”类,但是当尝试使用上面的调用时,它实际上调用了“TestPci”.“testing”方法。但是自动连接为“testWebClientService”的对象返回为空。我想创建对象,而不是返回 null。

新春版类:

@Service
@EnableConfigurationProperties(TestWebClientProperties.class)
@Configurable
public class TestPci{
    
    @Autowired
    private TestWebClientService testWebClientService;
        
    
    public Map<String, String> testing(String a, String b, String c) throws Exception {
        Map<String, String> map =  testWebClientService.find(a, b, c);
        System.out.println("**=="+map.get(0));
        return map;
    }
    }

添加用于从较新版本的spring调用TestPci类的junit:

@RunWith(SpringJUnit4ClassRunner.class)
@EnableConfigurationProperties(TestWebClientProperties.class)
@SpringBootTest(classes = { TestWebClientService.class, TestPci.class }, webEnvironment = WebEnvironment.NONE)
public class TestJunit {
    
    
    @MockBean(name="restTemplate")
     public RestTemplate              restTemplate;
     
     @Autowired
     private TestPci testPci;
    
    @Test
    public void ff() throws Exception {
        testPci.testing("1","1","1");
    }

}
4

0 回答 0