如何在Spring应用程序启动时调用自定义数据加载器

时间:2012-11-08 05:32:17

标签: java spring web-applications spring-roo

我正在尝试在应用程序启动时将一些数据加载到我的数据库中。我为此目的定义了一个bean

的applicationContext.xml

<bean class="com.project.loader.DataLoader" 
id="DataLoader" 
depends-on="entityManagerFactory" 
scope="singleton"/>

类:

@RooJavaBean
@RooConfigurable
public class DataLoader implements InitializingBean

它正在执行但是在第一个persist()方法被调用时,Spring会抛出以下错误:

Caused by: java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at com.project.lib.model.extensions.i18n.Locale_Roo_Jpa_ActiveRecord.entityManager_aroundBody0(Locale_Roo_Jpa_ActiveRecord.aj:19)
at com.project.lib.model.extensions.i18n.Locale_Roo_Jpa_ActiveRecord.ajc$interMethod$com_project_lib_model_extensions_i18n_Locale_Roo_Jpa_ActiveRecord$com_project_lib_model_extensions_i18n_Locale$entityManager(Locale_Roo_Jpa_ActiveRecord.aj:1)
at com.project.lib.model.extensions.i18n.Locale.entityManager(Locale.java:1)

当我以下列方式定义DataLoader时,它正常工作:

@Component
@Configurable
public class DataLoader implements ApplicationListener

但使用原始类型并不是一个好习惯,所以我想切换

我怎样才能让它发挥作用?

春季版:3.1

2 个答案:

答案 0 :(得分:0)

我已经通过将组件扫描定义移动到应用程序上下文的末尾来解决了这个问题,如建议here

答案 1 :(得分:0)

我使用Spring SmartLifecycle: http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/SmartLifecycle.html

我已经创建了一个很好地执行此操作的类,只需扩展并覆盖run方法:

public abstract class StartupService implements SmartLifecycle {
/** Logger for this class and subclasses */
protected static final Logger logger = LoggerFactory.getLogger(StartupService.class);

protected boolean running=false;

////////////////////// Lifecycle Methods \\\\\\\\\\\\\\\\\\
@Override
public void start() {
    try {
        logger.info("starting {}", this.getClass().getSimpleName());
        run();
    } catch (Exception e) {
        logger.error("failed to run importer", e);
    }
}

@Override
public void stop() {
    running=false;
}

@Override
public boolean isRunning() {
    return running;
}

////////////////////// SmartLifecycle Methods \\\\\\\\\\\\\\\\\\
@Override
public boolean isAutoStartup() {
    return true;
}

@Override
public void stop(Runnable callback) {
    stop();
    callback.run();
}

@Override
public int getPhase() {
    return 0;
}

public abstract void run() throws Exception;
}