简体   繁体   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?

I have a service interface called ABCService and its implementation called ABCServiceImpl. 我有一个名为ABCService的服务接口及其实现,称为ABCServiceImpl。

ABCService.class ABCService.class

package com.abc.service.ABCService;

public interface ABCService{
    //interface methods
}

ABCServiceImpl.class ABCServiceImpl.class

package com.abc.service.ABCServiceImpl; 

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

XYZ.class XYZ.class

package com.abc.util.XYZ;

public class XYZ{

  @Autowired
  ABCService abcService;

  //methods
}

application-context.xml 应用程序的context.xml

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

But when I am trying to use the autowired ABCService in class XYZ to access methods in interface ABCService, I get a null pointer exception. 但是,当我尝试在类XYZ中使用自动装配的ABCService访问接口ABCService中的方法时,我得到一个空指针异常。 I then removed the @Service annotation from ABCServiceImpl & added the implentation file in the application-context.xml as a bean & created a bean for class XYZ and gave reference of ABCServiceImpl's bean to bean of class XYZ ; 然后我从ABCServiceImpl中删除了@Service注释,并将application-context.xml中的实现文件作为bean添加并为类XYZ创建了一个bean,并将ABCServiceImpl的bean引用到了类XYZ的bean; it solved the issue 它解决了这个问题

application-context.xml 应用程序的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>

but I want to use the @Service annotation itself without explicitly defining a bean in application-context.xml. 但我想使用@Service注释本身而不在application-context.xml中显式定义bean。 How do I do it? 我该怎么做?

If you want to autowire beans without package scanning, or defining them in XML, then your only option is to do it programmatically using the Spring API... 如果你想在没有包扫描的情况下自动装配bean,或者用XML定义它们,那么你唯一的选择就是使用Spring API以编程方式进行...

This is possible using 这可以使用

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

Also if you want any @PostConstruct methods to be called, use 此外,如果您想要调用任何@PostConstruct方法,请使用

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

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

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