来自外部软件包的@Autowired Bean失败

时间:2019-02-24 22:04:46

标签: java spring spring-ioc

我有一个Java(Maven)pkg,带有接口(IHelloWorld)和实现(HelloWorld)

我已经确认,无论是否使用Spring IoC,我都可以使用该软件包,但是当我尝试使用自动装配时,应用程序崩溃了

我在做什么错了?

外部软件包:

package com.example.library;

public class HelloWorld implements IHelloWorld
{
    private String _name;

    public void setName(String name)
    {
        this._name = name;
    }

    public String getName()
    {
        return this._name;
    }

    public String greet()
    {
        return "Hello " + this._name + "!";
    }
}

在消耗大量的测试项目中,我可以手动创建对象,也可以使用“旧式” bean接线

config.xml:

<bean id="talk" class="com.example.library.HelloWorld">
    <property name="name" value="#{systemProperties['usr']}" />
</bean>

上下文帮助器类:

package com.example.demo;

import org.springframework.context.ApplicationContext;

public final class IoCHelper
{
    private static ApplicationContext _context;

    private IoCHelper() { }

    public static void setContext(ApplicationContext context) { _context = context; }

    public static ApplicationContext getContext() { return _context; }
}

主要:

IoCHelper.setContext(new ClassPathXmlApplicationContext("myApp.xml"));

测试课程:

package com.example.demo;

import com.example.library.IHelloWorld;

public class SomeClass
{
    private IHelloWorld _myObj;

    public void initTest()
    {
        Object obj = IoCHelper.getContext().getBean("talk");

        this._myObj = (IHelloWorld)obj;
    }

    public IHelloWorld getTest() { return this._myObj; }
}

控制器:

@RequestMapping("/test2")
public String TestMe2()
{
    SomeClass x = new SomeClass();

    x.initTest();
    return x.getTest().greet();
}

当我将@Component和@Autowired添加到测试类“ SomeClass”时,我的应用程序失败并出现错误

  

com.example.demo.SomeClass中的字段_myObj需要一个类型为“ com.example.library.IHelloWorld”的bean。

@Component
public class SomeClass
{
    @Autowired
    private IHelloWorld _myObj;

我在config xml中都尝试过,但都没有用

<context:annotation-config />
<context:component-scan base-package="com.example.library,com.example.demo" />

0 个答案:

没有答案
相关问题