springWeb项目启动时自动加载方法及web项目启动时不能获得spring的bean的解决方式

版权声明:此博客内容均是本人精心整理文档,方便大家学习交流,如有不妥之处,请联系我删除 https://blog.csdn.net/u012489091/article/details/81012043

方式一:利用注解的方式和构造方法

@Service("testService")
public class TestService {

    @Autowired
    private Service service;

    /**
     * spring在初始化bean的时候,就会执行这个线程
     * 而且,这个@Service这个注解也是可以用别的注解替代的,比如@Configuration等注解
     * @author zhangshuang-ds5
     */
    public TestService (){
        Thread thread = new Thread() {
            @Override
            public void run() {
                test();
            }
        };
        thread.start();//启动
    }

    public void test() {
        // TODO 写具体的业务
        service.test();
    }
}

方式二:利用spring的 InitializingBean 初始化数据
https://www.cnblogs.com/study-everyday/p/6257127.html

注意:还有一种就是通过web.xml的init,在项目启动的时候初始化我们想要启动的方法,但是这种时候,会导致我们的spring的bean获取不到,我们就可以通过下面的方式获取spring的bean。也就是通过实现ApplicationContextAware来获取bean
定义工具类:

package com.gomeplus.bs.service.order.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 提供获得spring的getBean的支持
 * @author zhangshuang-ds5
 */
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;  

    public void setApplicationContext(ApplicationContext applicationContext) {  
         SpringContextUtil.applicationContext = applicationContext;  
    }  

    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  

    public static Object getBean(String name) throws BeansException {  
        return applicationContext.getBean(name);  
    }  

}

修改项目启动配置文件,增加以下配置:

<!-- 提供获得springBean的支持 -->
<bean id="springContextsUtil" class="com.gomeplus.bs.service.order.utils.SpringContextUtil"></bean>
<!-- 启动文件默认初始化Test类 的 init 方法 -->
<bean id="test" class="com.test.Test" init-method="init" lazy-init="false">
    <!-- 此处是注入的属性 -->
    <property name="" value="" />
</bean>

代码初始化的类中使用以下代码调用:

class Test {
    // 此代码如果使用 @Autowire Service service; 是注入不进去的
    public void init() {
        // 通过这种方式获得service注入
        Service service = (Service) SpringContextUtil.getBean("service");
    }
}

猜你喜欢

转载自blog.csdn.net/u012489091/article/details/81012043
今日推荐