【问题标题】:How to use @Service annotated class as an @Autowired bean in another class which is outside the component scan package of the Service class?如何在Service类的组件扫描包之外的另一个类中使用@Service注释类作为@Autowired bean?
【发布时间】:2016-06-02 13:47:03
【问题描述】:

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

应用程序上下文.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;它解决了这个问题

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

【问题讨论】:

  • 是否要求 XYZ 类在包扫描服务之外?
  • @Adam :是的,XYZ 是一个实用程序类,我不想将该类放入服务包中。因此 XYZ 类将在 com.abc.util 包中

标签: java spring-mvc javabeans autowired


【解决方案1】:

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

这可以使用

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

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

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

【讨论】:

    猜你喜欢
    • 2016-02-01
    • 2019-01-29
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    相关资源
    最近更新 更多