如何在创建bean之后立即在gradle项目中使用@Configuration执行Java主类

时间:2015-07-28 17:23:39

标签: java spring gradle

我有一个实例化所有bean的配置类。我有一个主要课程 带有execute()的TestUpdator()。 我计划运行这个主类,当我做一个“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  
         }    
   }
}

这个类将在后台执行,并在战争运行时执行代码。

有没有办法以我的方式做到这一点,还是有另一种方式? 我用谷歌搜索过,但我找不到好的例子。

基本上我正在尝试做两件事, 1)当我做gradle tomcatRunWar时,它将启动tomcat并部署war 2)当它这样做时,它应该通过调用execute()

在后台运行主类(TestUpdator)

1 个答案:

答案 0 :(得分:0)

嗯,除非您正在开发的是一个Spring Boot项目,否则术语主类在这里毫无意义。

如果您在上下文初始化期间尝试在TestResultUpdator类中执行一段代码,则可以按照以下步骤操作:

1按如下方式组织TestResultUpdator课程:

@Bean
public class TestResultUpdator {

@PostConstruct
public void execute() {
        //CODE TO BE EXECUTED  
   }
}

2在代码中的某处获取此bean:

@Autowire
private TestResultUpdator bean;