欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用listener和beanfactoryaware实现bean的动态装载 博客分类: 备忘 springjmsactivemqbeanfactory 

程序员文章站 2024-02-06 11:43:40
...

首先,写一个类,继承Beanfactoryaware

public class SpringBeanAware implements BeanFactoryAware {

    public static BeanFactory beanFactory;

    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }
    public static Object getBean(String name) {
        return beanFactory.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return (T)beanFactory.getBean(name);
    }

    public static boolean containsBean(String name) {
        return beanFactory.containsBean(name);
    }
}


然后再spring的xml中声明:

<bean id="springBeanAware"
		class="com.iris.listener.SpringBeanAware" />


再次,在web.xml中声明监听器:
	<listener>
		<listener-class>
			com.iris.listener.IrisSedaDispatcher
		</listener-class>
	</listener>


注意:此处如果使用的是spring mvc3,切不可图省事把所有spring配置都和mvc配置放一起,那样将导致监听不到(除非你想加载两次配置~)


监听器的代码如下:

public class IrisSedaDispatcher implements ServletContextListener {
	private ServletContext context = null;

	public void contextDestroyed(ServletContextEvent event) {
		// Output a simple message to the server's console
		System.out.println("The Simple Web App. Has Been Removed");
		this.context = null;
	}

	public void contextInitialized(ServletContextEvent event) {
		this.context = event.getServletContext();
		System.out.println("启动好了我勒个去");

		DefaultListableBeanFactory beanregistry = (DefaultListableBeanFactory) SpringBeanAware.beanFactory;

		System.out.println("关注factory:" + beanregistry);

		 RootBeanDefinition define = new RootBeanDefinition(User.class);
		 PropertyValue username = new PropertyValue("username", "hellokitty");
		 MutablePropertyValues values = new
		 MutablePropertyValues(Arrays.asList(username));
		 define.setPropertyValues(values);
		
		 define.setScope(BeanDefinition.SCOPE_SINGLETON);
		 define.setAutowireCandidate(true);
		 beanregistry.registerBeanDefinition("usertest", define);
		 System.out.println((User) beanregistry.getBean("usertest"));
		 System.out.println("初始化好了");
    }
}


然后,你就可以再程序中按如下方法获取到你新注册的bean了:

System.out.println(SpringBeanAware.getBean("statisticsMessageProducer"));


以上。备忘。

注意:以上方法只能用来注册普通的bean,你如果想注册个jms的listener、listenercontain、queue什么的,那么还是放弃吧,除非你想把spring的解析这些东西的源码再写一遍。我就是这么搞了一天最后才发现自己就是个蛋。算吸取教训了。