【问题标题】:@Autowired not working in spring Integration@Autowired 在春季集成中不起作用
【发布时间】:2017-10-16 08:07:23
【问题描述】:

在服务实现中,在@Autowired 的帮助下,我在 serviceImpl 中注入了CollectInfo 对象,但我得到了NullPointerException

package net.group.cts.service.serviceImpl;
       @Service
        public class EmployeeImpl implements EmployeeService {       
            @Autowired
            CollectInfo  info;

            public void processData(){
                info.getName();
            }
        }

package net.group.cts.model;
    @Component
    public class CollectInfo  (){

        String name;

        public String getName(){
            name = name + "Mr.";
            return name;}
        }

    }

Xmlconfig.xml

<context:annotation-config/>
<context:component-scan base-package="net.group.cts"/>
<bean id="info"    class="net.group.emp.model.CollectInfo  "/>

【问题讨论】:

  • 你能分享 CollectInfo 类吗?检查你是否用@Component 注释了类
  • EmployeeImpl spring 容器是否托管?
  • @Vikram 是的,我定义了

标签: spring spring-integration


【解决方案1】:

如果该类不是 Spring bean,则不能在类中注入 bean。
EmployeeImpl 未使用任何 Spring bean stereotype 注释,例如 @Component@Service

EmployeeImpl上添加其中一个,并确保这两个类位于Spring扫描到的包内&lt;context:component-scan base-package="net.group.emp.service"/&gt; 应该没问题。

此外,两者都使用 @Component 注释 bean:

@Component
public class CollectInfo  (){...}

并在 Spring xml 配置中进行配置:

<bean id="info"  class="net.group.emp.model.CollectInfo  "/>

是多余的。
它将最终创建两个 bean:一个名为 collectInfo,另一个名为 info

我建议您尽可能选择注释而不是 xml 配置(这是大多数情况)。

【讨论】:

  • 我无法从 xml 中删除此 ,因为我将它用于网关目的,工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-28
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
相关资源
最近更新 更多