我有一个名为 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/