【问题标题】:Spring injection is not working if bean created manually in xml如果在 xml 中手动创建 bean,则 Spring 注入不起作用
【发布时间】:2016-04-16 17:08:12
【问题描述】:

我有以下豆子:

Bean.java

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Bean {

    private String arg;

}

Service.java

import lombok.Getter;
import javax.inject.Inject;

public class Service {

    @Inject @Getter
    private Bean bean;

    private String arg;

    public Service(String arg) {
        this.arg = arg;
    }
}

我是这样实例化这些东西的:

test-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean class="com.example.Bean">
          <constructor-arg value="bean param"/>
   </bean>

   <bean class="com.example.Service">
          <constructor-arg value="service param"/>
   </bean>

</beans>

但是当我创建上下文并查看 Service 实例内部的内容时:

    ApplicationContext context = new ClassPathXmlApplicationContext("test-context.xml");
    System.out.println(context.getBean(Bean.class));
    System.out.println(context.getBean(Service.class).getBean());

第二个System.out 给我null。

为什么Bean 实例没有被注入?

【问题讨论】:

    标签: java spring dependency-injection ioc-container


    【解决方案1】:

    我找到了原因,我只是忘记了&lt;context:annotation-config/&gt;,以便使@Inject 注释起作用。

    【讨论】:

      【解决方案2】:

      我不确定您将 XML 配置与注释混合和匹配的方法,它需要 &lt;context:annotation-config/&gt;。我会说你以一种或另一种方式做会更安全。如果您坚持使用 XML,则在 XML 定义中注入依赖项

      <bean id="foo" class="com.example.Bean">
          <constructor-arg value="bean param"/>
      </bean>
      
      <bean class="com.example.Service">
          <constructor-arg value="service param"/>
          <property name="bean" ref="foo" />
      </bean>
      

      或者用注释来做这一切

      @Component
      public class Bean {
          private String arg;
      
          public Bean(@Value("{constructorArg}") final String arg) {
              this.arg = arg;
          }
      }
      
      @Service
      public class Service {
      
          @Autowired @Getter
          private Bean bean;
      
          private String arg;
      
          public Service(@Value("{constructorArg}") String arg) {
              this.arg = arg;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 2015-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多