简体   繁体   中英

Can I make code run before the constructor using annotations

I am using Guice to create and inject instances in my application.

For testing purposes I created a class that is responsible for creating all the static instances needed for a specific test class and inject them. Let's call this class GuiceGraphBuilder.

I want to create and initiate the GuiceGraphBuilder before my mock / test class constructor is called, as some of my mock classes requires the injection to happen on construction time.

Currently I am using a static constructor that initiate GuiceGraphBuilder and populate bunch of static fields.

Is there a way to use some kind of annotation to make a code run before the constructor does? I have seen an answer that uses Guice, but this of course is not good in my case, since I want to create the Guice injector in the generated code.

I suppose you test using junit? Then you have the lifecycle hooks

  • @BeforeClass - run once before first test (use for static setup)
  • @Before - run before every test method
  • @After - run after each test method
  • @AfterClass - run once after all tests finished

I suppose that, arbitrary from guice, you will be able to solve your problem by matching init and clean up to the correct phase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM