繁体   English   中英

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

[英]How to use @Service annotated class as an @Autowired bean in another class which is outside the component scan package of the Service class?

我有一个名为ABCService的服务接口及其实现,称为ABCServiceImpl。

ABCService.class

package com.abc.service.ABCService;

public interface ABCService{
    //interface methods
}

ABCServiceImpl.class

package com.abc.service.ABCServiceImpl; 

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

XYZ.class

package com.abc.util.XYZ;

public class XYZ{

  @Autowired
  ABCService abcService;

  //methods
}

应用程序的context.xml

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

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

应用程序的context.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。 我该怎么做?

如果你想在没有包扫描的情况下自动装配bean,或者用XML定义它们,那么你唯一的选择就是使用Spring API以编程方式进行...

这可以使用

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM