使用代理TARGET_CLASS在原型bean内自动装配单例bean

时间:2016-06-24 06:20:14

标签: 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 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");
    }
}

此处:当我尝试访问SingletonBeanInnerSingletonBeanOuter - >原型的实例时,它会返回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_CLASS代理设置从SingletonBeanInner访问时,获取PrototypeBean的单例实例。

0 个答案:

没有答案