在Spring配置文件applicationcontext加载后启动某些服务

前段时间在项目中用到rabbitmq来进行开门红期间的流量削峰,当我们把发送消息和接收消息的代码写好后,发现了一个问题:


在后台逻辑处理过程中需要使用到Redis,但是从bean容器中获取Redis的类的时候会出现取不到的问题。。。后来我在Redis的类和监听类里面分别加上了日志输出来观察谁先被加载,结果发现不管怎样都是监听类先启动的,而后Redis类才被加载。
这个问题让我很是头疼,后来在网上搜到了关于ApplicationListener这个接口。

ApplicationListener是spring提供的接口,作用是在web服务器启动时去加载某些程序。

随后我用了下面的方法实现了在加载完applicationContext.xml配置中的所有bean后再来加载消息队列的
监听类。

@Component
public class StartLoader implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext ctx = contextRefreshedEvent.getApplicationContext();
            try { //启动消息队列监听
	            SimpleMessageListenerContainer listener = (SimpleMessageListenerContainer) ctx.getBean("listenerA");
	            listener.start();
       		}catch (Exception e){
                System.out.println("启动消息队列监听失败。",e);
            }
        }
}

就这样我们的监听类就在启动的时候成功的加载上Redis这个bean啦~

ApplicationContextSpring框架中的一个接口,它是BeanFactory的子接口,提供了更多的功能,例如国际化支持、事件传递等。ApplicationContext的实现类有很多,其中比较常用的有ClassPathXmlApplicationContext和FileSystemXmlApplicationContext。 在配置ApplicationContext时,需要先创建一个Spring配置文件,可以是XML格式或者Java Config格式。在配置文件中,需要开启注解开发功能,并扫描所有被注解标注的类所在的包。例如: ```xml <context:annotation-config /> <context:component-scan base-package="site.hanzhe" /> ``` 其中,`<context:annotation-config />`用于开启注解开发功能,`<context:component-scan>`用于扫描指定包下的所有被注解标注的类。 接下来,需要在配置文件中配置ApplicationContext。以ClassPathXmlApplicationContext为例,配置如下: ```xml <bean id="exampleBean" class="site.hanzhe.ExampleBean" /> <bean id="anotherBean" class="site.hanzhe.AnotherBean" /> <bean id="myService" class="site.hanzhe.MyServiceImpl"> <property name="exampleBean" ref="exampleBean" /> <property name="anotherBean" ref="anotherBean" /> </bean> <bean id="context" class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg value="SpringConfig.xml" /> </bean> ``` 其中,`<bean>`标签用于定义Bean,`<constructor-arg>`标签用于注入依赖。`<bean>`标签中的`class`属性指定了Bean的类名,`id`属性指定了Bean的唯一标识符。`<constructor-arg>`标签中的`value`属性指定了Spring配置文件的路径。 最后,在Java代码中,可以通过ApplicationContext获取Bean并调用其方法。例如: ```java ApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig.xml"); MyService myService = (MyService) context.getBean("myService"); myService.doSomething(); ``` 上述代码中,首先创建了一个ApplicationContext对象,然后通过`getBean()`方法获取了一个名为"myService"的Bean,并将其转换为MyService类型。最后,调用了MyService的`doSomething()`方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值