1. 程式人生 > >springWeb專案啟動時自動載入方法及web專案啟動時不能獲得spring的bean的解決方式

springWeb專案啟動時自動載入方法及web專案啟動時不能獲得spring的bean的解決方式

方式一:利用註解的方式和構造方法

@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");
    }
}