【问题标题】:Instantiate bean annotated ContextConfiguration annotation实例化 bean 注解的 ContextConfiguration 注解
【发布时间】:2013-10-18 08:21:21
【问题描述】:

我有以下 java 类:

@ContextConfiguration(locations = { "classpath:/pathToXml" })
public class AbstractServiceTest  extends AbstractTransactionalJUnit4SpringContextTests {
    @Autowired
    protected SessionFactory sessionFactory;
    @Autowired
    protected MyBean myBean;

    public Integer doSomething(){
       return myBean.returnVeryImportantInteger();
    }
        ...
}

如果我写new AbstractServiceTest ()

sessionFactory 为空。(在 pathToXml 中写入的 sessionFacory 信息)

我怎么能说 spring 它看到了来自"classpath:/pathToXml" 的配置?

    @ContextConfiguration(locations = { "classpath:/anotherPathToXml" })
    public class MyClass
        public void myMethod(){
           // I want to use here method doSomething from AbstractServiceTest class
        }
     }

【问题讨论】:

    标签: java spring spring-mvc configuration


    【解决方案1】:

    让 spring 为您实例化 AbstractServiceTest 并在您需要的地方自动装配它。 然后 Spring 将检查上下文配置并执行自动装配。

    既然我可以看到这是一个测试类,你是否使用SpringJUnit4ClassRunner (@RunWith(SpringJUnit4ClassRunner.class)) 运行它?

    【讨论】:

    • 我想在另一个类(B类)中使用这个类的方法。
    • 当您使用new 实例化自己的类时,这是发生的正常Java 机制,Spring 不会被调用并且无法知道,因此您的成员是null 是正常的。您需要在其他类中使用 @Autowired 才能让 Spring 配置正确的实例
    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多