当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Bean instantiation notification in Spring

问题描述:

I know Spring framework and have worked in it and have used ApplicationContext to instantiate and load beans.

Lets say I write the following piece of code

ApplicationContext context=new ClassPathXmlApplicationContext("appContext.xml");

Now, after the above statement, how do i get to know if the beans, that are defined in appContext.xml, has been instantiated and loaded by Spring?

Note : I want to know it before accessing any bean

网友答案:

Try retrieving one:

MyClass myClass = (MyClass) context.getBean("MyBean");
网友答案:

I agree with Reimeus, and @jbx's comment. If nothing is thrown you should be good to go. If you really want to be sure though, consider using a logger, or even some sort of AOP to trigger an event when a bean is created.

I think I know what you're getting at, and it's something that's hard for us to do as programmers. Dependency injection (What spring does by creating beans in an application context) takes away the step of explicitly creating beans (ie. "Thing something = new Thing()") and that can be frightening, especially in early development when not everything is working, and you're not sure why.

Your objects are instantiated. You've just got to trust that Spring is doing it's thing--it will let you know if it's not :D

(also check out the BeanFactoryPost processor http://javasourcecode.org/html/open-source/spring/spring-3.0.5/org/springframework/beans/factory/config/BeanFactoryPostProcessor.html , it will allow you to see what's there if you really want)

分享给朋友:
您可能感兴趣的文章:
随机阅读: