【问题标题】:Spring not able to instantiate bean with @ResourceSpring 无法使用 @Resource 实例化 bean
【发布时间】:2013-03-06 10:13:54
【问题描述】:

我正在运行这段代码。

public class TestIOC {

@Resource
University university;

public static void main(String[] arg)
{
    ApplicationContext context =
        new ClassPathXmlApplicationContext("service.xml");
    TestIOC ioc = new TestIOC();
    //ioc.university = (University)context.getBean("university");
    System.out.println(ioc.university);
}
}

这是我的 service.xml 文件。

<context:annotation-config />
<bean id="university" class="com.test.beans.University">
    <constructor-arg type = "int" value="1"   />
    <constructor-arg type = "java.lang.String" value="Some University"   />
    <constructor-arg type = "java.lang.String" value="Some City"   />

</bean>

如果我评论了 context.getBean("university");我无法打印大学的价值观。但使用 context.getBean("university");我可以打印输出。

我正在使用@Resource,但我仍然需要 getBean 方法来注入 bean。

【问题讨论】:

    标签: spring dependency-injection resources inversion-of-control javabeans


    【解决方案1】:

    这是因为TestIOC不是spring管理的。如果你想让@Resource 工作,那么你需要为TestIOC 创建一个bean 并使用它。

    将以下 bean 添加到 service.xml

    <bean id="testIOC" class="TestIOC"></bean>
    

    然后在java中像这样使用它

    TestIOC ioc = context.getBean(TestIOC.class);
    System.out.println(ioc.university);
    

    【讨论】:

      【解决方案2】:

      肯定是因为你没有在 Spring 上下文中配置 TestIOC 类,所以 Spring 对此无能为力。您应该将其作为 bean 添加到 service.xml。与这个问题无关的一件事是,如果您使用&lt;Context:annotation-config&gt; 并使用@Resource 注入bean,那么bean 必须在xml 中配置,而不是带有组件的注释bean。有时会与&lt;context:component-scan/&gt;混淆

      【讨论】:

        【解决方案3】:

        @资源

        Indicates that a method or field should be injected with a 
        named resource (by default, another bean).
        

        在您的情况下,Spring 将尝试连接“大学” 引用 ID 为“university”的 bean 的属性。

        【讨论】:

          猜你喜欢
          • 2018-08-09
          • 2012-11-08
          • 1970-01-01
          • 2018-09-05
          • 2015-07-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多