让Spring @Autowired和@postconstuct工作

时间:2016-10-25 08:06:06

标签: spring spring-ioc

我正在尝试将新bean引入现有项目

当前bean

package w.x.y.z.pkgA
@Component
public class BeanA implements InterfaceA {

}

我正在尝试将新Bean添加到w.x.y.z.pkgB

package w.x.y.z.pkgB
public class BeanB implements InterfaceB {

    @Autowired
    private BeanA beanA

    @PostConstruct
    public void postConstructMethod() {
        //Call some method in BeanA
    }
}

BeanB我要访问BeanA数据,在BeanB帖子构建中我想要BeanB注册BeanA。所以我想打电话给BeanA方法

所有这些包都打包为jar 和spring context xml是

<context:annotation-config />
<context:component-scan base-package="w.x.y.z.pkgA,w.x.y.z.pkgB" />
<bean id="beanb" clas="w.x.y.z.pkgB.BeanB"></bean>

但是在部署期间,我在创建状态

中获得了关于bean的异常
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'context': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:347)
at w.x.y.z.BeanA<init>(BeanA.java:25)
at w.x.y.z.BeanB.<init>(BeanB.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)

我也尝试删除@Autowired并使用BeanA获取getBeanFactory().getBean(BeanA.class)对象。但我得到同样的错误。

如果我从xml文件中删除bean条目,它会被正确部署但是post构造永远不会被调用,因为它不再是bean。

BeanA完全不依赖于BeanB。没有参考?

当2个bean在同一个jar中时,有没有办法让@Autowired@PostConstruct工作?

1 个答案:

答案 0 :(得分:0)

您从w.x.y.z包中将bean声明为<bean id="beanb" clas="w.x.y.z.BeanB">

尝试

package w.x.y.z
@Component
public class BeanA implements InterfaceA {

}


package w.x.y.z
public class BeanB implements InterfaceB {

    private BeanA beanA

    @PostConstruct
    public void postConstructMethod() {
        //Call some method in BeanA
    }

    // Getters and Setters
}

<context:annotation-config />
<context:component-scan base-package="w.x.y.z" />
<bean id="beanb" clas="w.x.y.z.BeanB">
    <property name="beanA" value="beanA"/> <!-- Spring will create beanA as it is annotated with @Component -->
</bean>