Java 使用代理目标类在原型bean中自动连接单例bean

Java 使用代理目标类在原型bean中自动连接单例bean,java,spring,spring-annotations,Java,Spring,Spring Annotations,我有以下三节课 @Service(value="singleOuter") public class SingletonBeanOuter { @Autowired public SingletonBeanInner sbi; @Autowired public PrototypeBean pb; public SingletonBeanOuter() { System.out.println("Singleton OUTER Bean i

我有以下三节课

@Service(value="singleOuter")
public class SingletonBeanOuter {
    @Autowired
    public SingletonBeanInner sbi;
    @Autowired
    public PrototypeBean pb;
    public SingletonBeanOuter()
    {
    System.out.println("Singleton OUTER Bean instance creation");
    }
}

@Service(value="prot")
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
public class PrototypeBean{
    public PrototypeBean()
    {
        System.out.println("Prototype Bean instance creation");
    }
    @Autowired
    public SingletonBeanInner sbi;
}

@Service(value="singleInner")
public class SingletonBeanInner {
    public SingletonBeanInner()
    {
        System.out.println("Singleton Bean INNER instance creation");
    }
}
这里:当我试图通过
SingletonBeanOuter
->prototype访问
singletonbeanner
的实例时,它返回null

public class TestMain {
    public static void main(String args[])
    {
         ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
         SingletonBeanOuter a = context.getBean("singleOuter", SingletonBeanOuter.class);
                System.out.println("=================================================================");
    System.out.println(a);
    System.out.println(a.sbi);
    System.out.println(a.pb);
    System.out.println(a.pb.sbi); //Returns null
    System.out.println("=================================================================");
    SingletonBeanOuter b = context.getBean("singleOuter", SingletonBeanOuter.class);
    System.out.println(b);
    System.out.println(b.sbi);
    System.out.println(b.pb);
    System.out.println(b.pb.sbi); //Returns null
    }
}

我在这里的目的是在使用TARGET_类代理设置从
PrototypeBean
访问
singletonbeanner
时获取它的singleton实例。

,这是意料之中的。
a.pb
b.pb
是实际实例
pb
的代理。您得到的是代理的字段,而不是实际的实例。基本上,您所做的不会与代理一起工作。您必须将字段设置为私有并提供getter,这样它才能正常工作。这是意料之中的。
a.pb
b.pb
是实际实例
pb
的代理。您得到的是代理的字段,而不是实际的实例。基本上,您所做的不会与代理一起工作。您必须将字段设置为私有并提供getter,这样才能工作。