How can I get a list of instantiated beans from Spring?

前端 未结 6 766
挽巷
挽巷 2020-12-05 07:50

I have several beans in my Spring context that have state, so I\'d like to reset that state before/after unit tests.

My idea was to add a method to a helper class wh

6条回答
  •  再見小時候
    2020-12-05 08:37

    I've created a gist ApplicationContextAwareTestBase.

    This helper class does two things:

    1. It sets all internal fields to null. This allows Java to free memory that isn't used anymore. It's less useful with Spring (the Spring context still keeps references to all the beans), though.

    2. It tries to find all methods annotated with @After in all beans in the context and invokes them after the test.

    That way, you can easily reset state of your singletons / mocks without having to destroy / refresh the context.

    Example: You have a mock DAO:

    public void MockDao implements IDao {
    
        private Map database = Maps.newHashMap();
    
        @Override
        public Foo byId( Long id ) { return database.get( id ) );
    
        @Override
        public void save( Foo foo ) { database.put( foo.getId(), foo ); }
    
        @After
        public void reset() { database.clear(); }
    }
    

    The annotation will make sure reset() will be called after each unit test to clean up the internal state.

提交回复
热议问题