我有一个实例化所有 bean 的配置类。我有一个主课 TestUpdator() 和一个execute()。 我计划在执行“gradle tomcatRunWar”来运行 war 时运行这个主类,它将生成 bean 并在主类中运行execute()。 示例。
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "<packageName>", excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Service.class) })
@EnableSolrRepositories(basePackages = "<solrPackageName>", multicoreSupport = true)
public class JobConfig {
private static final Logger logger = LoggerFactory.getLogger(JobConfig.class);
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
....
}
@Bean
public SpringContextAware springContextAware() throws Exception {
.....
}
.....
//MAIN CLASS BEAN TO BE EXECUTED
@Bean(destroyMethod="shutdown")
public TestResultUpdator testResultUpdator() throws Exception {
TestResultUpdator resultUpdator = new TestResultUpdator();
/**
Bunch of dependencies for this bean
**/
resultUpdator.execute(); //call to execute()
return resultUpdator;
}
TestUpdator 类如下所示
public class TestResultUpdator {
//Variables
public static void main(String args[]) throws Exception {
//NOT SURE WHAT TO ADD HERE SINCE THE execute() will be called from the class above. But this is what I have right now commented out.
// ApplicationContext appContext = new AnnotationConfigApplicationContext(JobConfig.class);
// TestResultUpdator updator = appContext.getBean(TestResultUpdator.class);
// updator.execute();
}
public void execute() throws Exception {
logger.info("INSIDE EXECUTE FOR TEST UPDATOR!!!!");
while(true) {
//CODE TO BE EXECUTED
}
}
}
此类将在后台执行,并在 war 运行时执行代码。
有没有办法按照我的方式做到这一点,或者有其他方法吗? 我用谷歌搜索了一下,但找不到很好的例子。
基本上我想做两件事, 1)当我执行gradle tomcatRunWar时,它将启动tomcat并部署war 2)当它这样做时,它应该通过调用execute()在后台运行主类(TestUpdator)
最佳答案
好吧,除非您正在开发 Spring Boot 项目,否则术语“主类”在这里毫无意义。
如果您尝试在上下文初始化期间执行 TestResultUpdator 类中的一段代码,可以按照以下步骤操作:
1 按如下方式组织TestResultUpdator
类:
@Bean
public class TestResultUpdator {
@PostConstruct
public void execute() {
//CODE TO BE EXECUTED
}
}
2 在代码中的某个位置获取此 bean:
@Autowire
private TestResultUpdator bean;
关于java - 如何在创建 bean 后立即在 gradle 项目中使用 @Configuration 执行 Java 主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31683192/