java - 如何在Service类的组件扫描包之外的另一个类中使用@Service注释的类作为@Autowired bean?

标签 java spring-mvc javabeans autowired

我有一个名为 ABCService 的服务接口(interface)及其名为 ABCServiceImpl 的实现。

ABCService.class

package com.abc.service.ABCService;

public interface ABCService{
    //interface methods
}

ABCServiceImpl.类

package com.abc.service.ABCServiceImpl; 

@Service
public class ABCServiceImpl implements ABCService{
     // implemented methods
}

XYZ.类

package com.abc.util.XYZ;

public class XYZ{

  @Autowired
  ABCService abcService;

  //methods
}

应用程序上下文.xml

<context: annotation-config>
<context: component-scan base-package="com.abc.service, com.abc.util"/>

但是当我尝试使用 XYZ 类中的 Autowiring ABCService 来访问 ABCService 接口(interface)中的方法时,出现空指针异常。 然后,我从 ABCServiceImpl 中删除了 @Service 注释,并在 application-context.xml 中添加了实现文件作为 bean,并为类 XYZ 创建了一个 bean,并将 ABCServiceImpl 的 bean 的引用提供给了类 XYZ 的 bean;它解决了问题

应用程序上下文.xml

<bean id="abcService" class="com.abc.service.ABCServiceImpl" />

<bean id="xyz" class="com.abc.util.XYZ" >
    <property name="abcService" ref="abcService"></property>
</bean>

但我想使用 @Service 注释本身,而不在 application-context.xml 中显式定义 bean。我该怎么做?

最佳答案

如果您想在不扫描包的情况下 Autowiring bean,或者在 XML 中定义它们,那么您唯一的选择就是使用 Spring API 以编程方式完成...

这可以使用

XYZ bean = new XYZ();
context.getAutowireCapableBeanFactory().autowireBean(bean);

此外,如果您希望调用任何 @PostConstruct 方法,请使用

context.getAutowireCapableBeanFactory().initializeBean(bean, null);

关于java - 如何在Service类的组件扫描包之外的另一个类中使用@Service注释的类作为@Autowired bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593758/

相关文章:

java - 集合排序 - 找不到符号

java - Spring 安全和 Thymeleaf 不起作用

java - 即使定义了请求映射,为什么请求调度程序仍在 spring mvc 中查找 View ?

python - JMeter - 在调用每个 HTTP 请求采样器之前运行 python 脚本

java ejb jsp未报告异常

java - 当 editText 上的 setText TextWatcher.onTextChanged 未调用时

java - 使用 Java 邮件 API 阅读电子邮件时引用/打印的未知编码

java - 如何使用注释在 Spring 中加载系统属性?

spring-mvc - 通过 STS(eclipse) 建议(红色标记)它们是什么意思

java - 即使 bean 已初始化,@Required 也会导致异常