Java 如何在服务类的组件扫描包之外的另一个类中使用@Service注释类作为@autowiredbean?
我有一个名为ABCService的服务接口,它的实现名为ABCServiceImpl ABCService.classJava 如何在服务类的组件扫描包之外的另一个类中使用@Service注释类作为@autowiredbean?,java,spring-mvc,javabeans,autowired,Java,Spring Mvc,Javabeans,Autowired,我有一个名为ABCService的服务接口,它的实现名为ABCServiceImpl ABCService.class package com.abc.service.ABCService; public interface ABCService{ //interface methods } ABCServiceImpl.class package com.abc.service.ABCServiceImpl; @Service public class ABCServiceIm
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类
package com.abc.util.XYZ;
public class XYZ{
@Autowired
ABCService abcService;
//methods
}
application-context.xml
<context: annotation-config>
<context: component-scan base-package="com.abc.service, com.abc.util"/>
<bean id="abcService" class="com.abc.service.ABCServiceImpl" />
<bean id="xyz" class="com.abc.util.XYZ" >
<property name="abcService" ref="abcService"></property>
</bean>
但是当我试图使用类XYZ中的自动连接ABCService来访问接口ABCService中的方法时,我得到了一个空指针异常。
然后,我从ABCServiceImpl中删除@Service注释,并将实现文件作为bean添加到application-context.xml中,为XYZ类创建了一个bean,并将ABCServiceImpl的bean引用给XYZ类的bean;它解决了这个问题
application-context.xml
<context: annotation-config>
<context: component-scan base-package="com.abc.service, com.abc.util"/>
<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中定义bean,那么您唯一的选择就是使用Spring API以编程方式完成 这是可能的使用
XYZ bean = new XYZ();
context.getAutowireCapableBeanFactory().autowireBean(bean);
另外,如果希望调用任何@PostConstruct方法,请使用
context.getAutowireCapableBeanFactory().initializeBean(bean, null);
如果您想在不扫描包或在XML中定义bean的情况下自动连接bean,那么您唯一的选择就是使用SpringAPI以编程方式进行连接 这是可能的使用
XYZ bean = new XYZ();
context.getAutowireCapableBeanFactory().autowireBean(bean);
另外,如果希望调用任何@PostConstruct方法,请使用
context.getAutowireCapableBeanFactory().initializeBean(bean, null);
类XYZ必须在包扫描服务之外吗?@Adam:是的,XYZ是一个实用类,我不想将该类放在服务包中。因此,XYZ类将位于com.abc.util包中。是否要求XYZ类位于包扫描服务之外?@Adam:是的,XYZ是一个实用程序类,我不想将该类放入服务包中。因此,XYZ类将位于com.abc.util包中